Unity get注入依赖项的服务类型 [英] Unity get Type of the service where the dependecy gets injected

查看:120
本文介绍了Unity get注入依赖项的服务类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to get, in Unity, the Type of the service where the dependecy gets injected?

Ninject中,您可以这样操作:

In Ninject you can do it like this:

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中实现相同的功能?

How can the same thing be implemented in Unity?

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

Here is what i have, but i do not have access to any context

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

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

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

推荐答案

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

You have to register your Service (whose type then gets reported to the injected dependency's constructor) with a special InjectionConstructor.

无耻地复制自己的答案(请参阅详细信息

Shamelessly copying my own answer (see details 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 );
    }
}

这篇关于Unity get注入依赖项的服务类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆