是否有可能在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);
});
答案 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 );
}
}