unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

Add Support for Custom Resolution #32

Closed spasarto closed 5 years ago

spasarto commented 5 years ago

I would like to discuss the possibility of adding the ability to customize type resolution. As of right now, the current implementation of Resolve looks like this:

    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch  { /* Ignore */}

        return null;
   }

This works for simple cases, but it doesn't allow us to pass in additional values into the resolution - names or resolver overrides. It may also be nice to respond to resolution errors. For reference, here is the current Unity Resolve method:

 public object Resolve(Type typeToBuild, string nameToBuild, params ResolverOverride[] resolverOverrides);

One possibility is to add support for IOptions<ResolutionOptions>, where ResolutionOptionslooks like this:

 public class ResolutionOptions
 {
      public Fun<IUnityContainer, Type, object> Resolve {get;set;}
 }
ENikS commented 5 years ago

You have several options here:

spasarto commented 5 years ago

Thanks for the reply.

The first two cases address registration overrides, which is a different scenario. The third option requires me to do the resolution, which doesn't work when code I don't control is performing the resolution.

For example, let's say I have a web project, and I register my types normally. However for certain web requests, I want to resolve a different set of dependencies (ie, dryrun/beta implementations/regional cases, etc). Because I don't have access to type resolution, I am stuck resolving whatever I registered. This pushes the burden to all of my implementations to know if they need to handle this other case. I would prefer to pass in a ResolverOverride to unity's resolution that informs the container to resolve the second set of dependencies, when appropriate.

Hopefully that better explains the need for this customization.

ENikS commented 5 years ago

It could be simply done by creating either IBuildPlanCreatorPolicy or IBuildPlanPolicy factories.

These will have access to resolver overrides you want to pass so you could customize resolution to your liking.

spasarto commented 5 years ago

Fair point. We can close this issue in favor of those suggestions.