[英]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.