如何获取在Unity中注入的对象的类型?

时间:2017-03-27 20:40:30

标签: c# reflection dependency-injection unity-container

我有一个在其构造函数中接收另一种类型的类型,它通常是创建它的对象的类型,例如:

public class Logger {
    public Logger(Type parent) { ... }
}

我想指示Unity解析Logger将构造函数作为参数传递给需要它的对象的类型。类似的东西:

// ... would be some directive to tell Unity to use the type that
/// depends on Logger
container.RegisterType<Logger>(new InjectionConstructor(...));

因此,当我尝试解析MyService时:

public MyService {
    public MyService(Logger logger) { ... }
}

它将返回:

var logger = new Logger(typeof(MyService));
return new MyService(logger);

有可能吗?还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

实际上,你可以这样做:

internal class Program
{
    static void Main( string[] args )
    {
        var container = new UnityContainer();
        container.RegisterType<IInterface, Implementation>( new MyInjectionConstructor() );

        // this instance will get a logger constructed with loggedType == typeof( Implementation )
        var instance = container.Resolve<IInterface>();
    }
}

internal class MyInjectionConstructor : InjectionMember
{
    public override void AddPolicies( Type serviceType, Type implementationType, string name, IPolicyList policies )
    {
        policies.Set<IConstructorSelectorPolicy>( new MyConstructorSelectorPolicy(), new NamedTypeBuildKey( implementationType, name ) );
    }
}

internal class MyConstructorSelectorPolicy : DefaultUnityConstructorSelectorPolicy
{
    protected override IDependencyResolverPolicy CreateResolver( ParameterInfo parameter )
    {
        if( parameter.ParameterType == typeof( ILogger ) )
        {
            return new LiteralValueDependencyResolverPolicy( new Logger( parameter.Member.DeclaringType ) );
        }
        return base.CreateResolver( parameter );
    }
}

internal interface ILogger
{
}

internal class Logger : ILogger
{
    public Logger( Type loggedType )
    {
    }
}

internal interface IInterface
{
}

internal class Implementation : IInterface
{
    public Implementation( ILogger logger )
    {
    }
}

这只是概念代码的证明,在生产使用之前可能需要稍微改进一下......