Search code examples
c#dependency-injectionunity-container

How to inject a Type instead of an instance into a constructor using Unity


Is it possible to inject a type into a constructor instead of an instance? If so how is this achieved? I want to avoid explicitly registering a factory method or resolving an instance in situ if possible.

public interface IJob { }
public class TheJob : IJob { }

public interface IService
{
    string GetTypeDesc();
}

public class Service : IService
{
    private Type _jobType;

    public Service(Type jobType)
    {
        _jobType = jobType;
    }

    public string GetTypeDesc()
    {
        return _jobType.ToString();
    }
}

It seems even when registering the type with explicit constructor definition, Unity wants to inject an instance into the type place holder.

Type jobType = typeof(TheJob);    
(new UnityContainer()).RegisterType<IService, Service>(new InjectionConstructor(jobType));

Solution

  • The constructor of InjectionConstructor takes an array of objects. If the type of an object passed to the constructor of InjectionConstructor (in the array) is of type Type, unity will try to resolve that type and then pass the result into the constructor (of 'Service` for example).

    For example, if you use new InjectionConstructor(typeof(IMyOtherService)), then unity will expect that the constructor of Service takes an instance of type IMyOtherService and will use the container to resolve such type. In other words Type is a special case that you need to handle in a specific way.

    To solve your issue, you should tell Unity that the Type you are passing is actually a constructor parameter. You can do this like this:

    new InjectionConstructor(new InjectionParameter(jobType))
    

    This forces unity to treat jobType as a constructor parameter.

    For more details see the InjectionParameterValue.ToParameter method here: https://github.com/unitycontainer/unity/blob/master/source/Src/Unity-CoreClr/Injection/InjectionParameterValue.cs