简体   繁体   English

温莎城堡注册开放式通用ILogger

[英]Castle Windsor registering open generics ILogger

I have Simple Injector registration of my: 我有我的简单注射器注册:

container.RegisterConditional(typeof(ILogManager),
c => typeof(LogManager<>).MakeGenericType(c.Consumer.ImplementationType),
Lifestyle.Singleton,
c => true);

I need to register same LogManager in different project using Castle Windsor. 我需要使用Castle Windsor在不同的项目中注册相同的LogManager。

I have tried 我努力了

container.Register(Component.For(typeof(ILogger))
            .ImplementedBy(typeof(Log4NetLogger<>).MakeGenericType())
            .LifeStyle.Singleton.Start());

Cannot make it working. 无法使其正常运行。

Unfortunately this is more complicated with Castle. 不幸的是,这与Castle相比更为复杂。 But you can achieve the same result with SubDependencyResolver: 但是您可以使用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);
    }
}

than add it into the kernel: 而不是将其添加到内核中:

Kernel.Resolver.AddSubResolver(new LoggerResolver())

Another way is to use GenericImplementationMatchingStrategy. 另一种方法是使用GenericImplementationMatchingStrategy。 This one will work also in situation if LogManager has some dependencies: 如果LogManager具有某些依赖项,则此选项也可以工作:

public class OpenGenericAncestorMatchingStrategy : IGenericImplementationMatchingStrategy
{
    public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
    {
        return new[] { context.Handler.ComponentModel.Implementation };
    }
}

and registration: 和注册:

container.Register(Component.For<ILogger>().ImplementedBy(typeof(LogManager<>), new OpenGenericAncestorMatchingStrategy()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM