我有一个简单的注塑器注册:
container.RegisterConditional(typeof(ILogManager),
c => typeof(LogManager<>).MakeGenericType(c.Consumer.ImplementationType),
Lifestyle.Singleton,
c => true);
我需要注册相同的LogManager在不同的项目使用城堡温莎。
我试过了
container.Register(Component.For(typeof(ILogger))
.ImplementedBy(typeof(Log4NetLogger<>).MakeGenericType())
.LifeStyle.Singleton.Start());
不能让它起作用。
发布于 2017-09-21 14:09:42
不幸的是,卡塞尔的情况更加复杂。但是,您可以使用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()));
https://stackoverflow.com/questions/46341503
复制相似问题