我有简单的喷油器注册:
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());
无法使其工作。
不幸的是,这对城堡更为复杂。但是,您可以使用亚依赖性质量验证者获得相同的结果:
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()));