Unity获取依赖注入的服务类型

时间:2017-11-14 11:03:44

标签: c# ninject unity-container

是否有可能在Unity中获得依赖注入的服务类型?

Ninject中你可以这样做:

kernel.Bind<ILogger>().ToMethod((context) =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // Eg: MyApplication.PeopleRepository
    string memberType = context?.Request?.Target?.Member?.DeclaringType?.FullName;

    return new LoggerMemberTypeDecorator(logger, memberType);
});

如何在Unity中实现同样的事情?

这是我所拥有的,但我无法访问任何context

container.RegisterType<ILogger>(new InjectionFactory(u =>
{
    ILogger logger = HttpContextLoggerFactory.GetInstance();

    // how to get it?
    string memberType = "";

    return new LoggerMemberTypeDecorator(logger, memberType);
});

1 个答案:

答案 0 :(得分:0)

您必须使用特殊InjectionConstructor注册您的服务(其类型然后报告给注入的依赖项的构造函数)。

无耻地复制我自己的答案(见详情here):

container.RegisterType<IInterface, Implementation>( new MyInjectionConstructor() );

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 );
    }
}