Unity get Type of the service where the dependecy

2019-08-18 14:30发布

问题:

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

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

How can the same thing be implemented in Unity?

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

回答1:

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