[英]Castle Windsor registering open generics ILogger
我有我的簡單注射器注冊:
container.RegisterConditional(typeof(ILogManager),
c => typeof(LogManager<>).MakeGenericType(c.Consumer.ImplementationType),
Lifestyle.Singleton,
c => true);
我需要使用Castle Windsor在不同的項目中注冊相同的LogManager。
我努力了
container.Register(Component.For(typeof(ILogger))
.ImplementedBy(typeof(Log4NetLogger<>).MakeGenericType())
.LifeStyle.Singleton.Start());
無法使其正常運行。
不幸的是,這與Castle相比更為復雜。 但是您可以使用SubDependencyResolver達到相同的結果:
public class LoggerResolver : ISubDependencyResolver
{
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
return dependency.TargetType == typeof(ILogger);
}
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
var logger = typeof(LogManager<>).MakeGenericType(model.Implementation);
return Activator.CreateInstance(logger);
}
}
而不是將其添加到內核中:
Kernel.Resolver.AddSubResolver(new LoggerResolver())
另一種方法是使用GenericImplementationMatchingStrategy。 如果LogManager具有某些依賴項,則此選項也可以工作:
public class OpenGenericAncestorMatchingStrategy : IGenericImplementationMatchingStrategy
{
public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
{
return new[] { context.Handler.ComponentModel.Implementation };
}
}
和注冊:
container.Register(Component.For<ILogger>().ImplementedBy(typeof(LogManager<>), new OpenGenericAncestorMatchingStrategy()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.