How to inject type instead of instance into constructor using Unity

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

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 that even when registering a type with an explicit constructor definition, Unity wants to insert an instance into the type holder.

Type jobType = typeof(TheJob);    
(new UnityContainer()).RegisterType<IService, Service>(new InjectionConstructor(jobType));
+4
source share
2 answers

The constructor InjectionConstructoraccepts an array of objects. If the type of the object passed to the constructor InjectionConstructor(in the array) is of type Type, unity will try to resolve this type, and then pass the result to the constructor (for example, "Service").

, new InjectionConstructor(typeof(IMyOtherService)), , Service IMyOtherService . , Type - , .

, Unity, Type, , . :

new InjectionConstructor(new InjectionParameter(jobType))

jobType .

. InjectionParameterValue.ToParameter : https://github.com/unitycontainer/unity/blob/master/source/Src/Unity-CoreClr/Injection/InjectionParameterValue.cs

+1

?

A System.Type , , System.String System.Int32. , ( ) . DI .

, Unity. , InjectionConstructor ( ):

.RegisterType<IService, Service>(new InjectionConstructor(jobType))

InjectionFactory:

.Register<IService>(new InjectionFactory(c => new Service(jobType)))
+1

Source: https://habr.com/ru/post/1685607/


All Articles