Castle Windsor - 传递Type作为构造函数参数

时间:2012-03-21 13:27:08

标签: c# .net castle-windsor

我有一个以Type作为构造函数参数的类。如何在Windsor容器中注册?

   public Class NLogLogger : ILogger
   {
      private NLog.Logger _logger;  
      public NLogLogger(Type type)
      {
           _logger = NLog.LogManager.GetLogger(type.FullName);
      }
    ...
   }

我试图以这种方式注册:

            container.Register(Component.For(typeof(ILogger))
                                .ImplementedBy(typeof(NLogLogger))
                                .LifestyleTransient()
                                .DependsOn(new Hashtable
                                            {
                                                {"type", ???}
                                            }));

我需要填写???。我无法弄清楚如何在那里传递调用类的Type

1 个答案:

答案 0 :(得分:2)

<强>更新

通过您的更新,您希望注入类型,以便您可以使用它进行日志记录。有两种解决方案。

public class ClassDependentOnLogger
{
    private ILogger _logger;  
    public ClassDependentOnLogger(ILogger logger)
    {
        _logger = logger;
    }

    ....

}

1 - 使用温莎SubDependancyResolver。下面的示例显示了如何返回和ILog的实例,但如果您想要这样做,您可以轻松地调整它以返回Type:

public class LoggerResolver : ISubDependencyResolver
{
    private readonly IKernel kernel;

    public LoggerResolver( IKernel kernel )
    {
        this.kernel = kernel;
    }

    public object Resolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, Castle.Core.ComponentModel model, DependencyModel dependency )
    {
        return NLog.LogManager.GetLogger(model.Implementation.FullName);
    }

    public bool CanResolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, Castle.Core.ComponentModel model, DependencyModel dependency )
    {
        return dependency.TargetType == typeof( ILogger );
    }
}

//Register the sub dependency resolver. This looks cleaner if you do it via a
//Facility but that's a whole other class
Container.Kernel.Resolver.AddSubResolver( new LoggerResolver( Kernel ) );

2 - 使用温莎LoggingFacility

您的示例中不需要NLoggerClass。