user1178376
user1178376

Reputation: 978

Castle Windsor - passing Type as constructor parameter

I have a class that takes Type as a constructor parameter. How can I register this in the Windsor container?

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

I am trying to register it this way:

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

I need to fill in the ???. I could not figure out how I can pass the calling class's Type there.

Upvotes: 1

Views: 1085

Answers (1)

Bronumski
Bronumski

Reputation: 14272

Update

Going by your update you want to inject the type so that you can use it for logging. There are two solutions.

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

    ....

}

1 - Use a Windsor SubDependancyResolver. The example below shows how to return and instance of an ILog but you could easily adapt it to return a Type instead if that is what you wanted to do:

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 - Use the Windsor LoggingFacility

There is no need for the NLoggerClass described in your example.

Upvotes: 2

Related Questions