Autofac TypedParameter的Unity替代品

时间:2017-03-21 15:32:06

标签: c# inversion-of-control unity-container autofac ioc-container

简短问题:如何在Unity中的Autofac文档部分Passing Parameters to Resolve中实现TypedParameter的相同功能?

一些背景知识:我们需要解析重命名基类的构造函数参数的继承类。这个参数无法解析,必须传入。我们知道继承的类只有可以解析的类型和一个基类构造函数参数。

亲切的问候, 杰夫

1 个答案:

答案 0 :(得分:0)

您可以像这样创建自己的TypedParameter

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

                    // this will be created with this MyLogger instance
        var instance = container.Resolve<IInterface>( new TypedParameter( typeof(ILogger), new MyLogger() ) );
    }
}

internal class TypedParameter : ResolverOverride
{
    private readonly Type _type;
    private readonly InjectionParameterValue _value;

    public TypedParameter( Type type, object value )
    {
        _type = type;
        _value = InjectionParameterValue.ToParameter( value );
    }

    public override IDependencyResolverPolicy GetResolver( IBuilderContext context, Type dependencyType )
    {
        ConstructorArgumentResolveOperation currentOperation = context.CurrentOperation as ConstructorArgumentResolveOperation;
        if ( currentOperation != null )
        {
            var parameter = currentOperation.TypeBeingConstructed.GetConstructors().Single().GetParameters().Single( x => x.Name == currentOperation.ParameterName );
            if (parameter.ParameterType == _type)
                return _value.GetResolverPolicy( dependencyType );
        }

        return null;
    }
}

// note that this is not registered with unity, is has to come from TypedParameter
internal class MyLogger : ILogger
{
}

internal interface ILogger
{
}

internal interface IInterface
{
}

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

没有生产就绪,但如果构造的类型只有一个构造函数,它就可以工作。但是你必须要小心,因为这些覆盖会对一个Resolve调用中创建的所有依赖项起作用。