1

I have a class whose constructor looks like

public class Foo(NLog.Logger logger)

I am using StructureMap 2.6.4.1 to do dependency injection (via constructor injection entirely, no property injection). I am using NLog for my logging. One of the nice features of NLog is that one can route log events to different targets via the loggers having names. It's very flexible, therefore, to name the loggers after the owning type's fully qualified name (In the example above, it would be <namespace>.Foo)

Castle Windsor's logging facility will supply a logger to the instances that require them, named for the class of the owning instance.

However, I haven't been able to get StructureMap to do this.

I've tried the EnrichWith((context, type) => {}) method, but context.ParentType is always null. Here's an example of my registry:

public class InfrastructureRegistry : Registry
{
    public InfrastructureRegistry()
    {
        For<NLog.Logger>().Use<NLog.Logger>()
            .EnrichWith((context, pluginType) => 
                NLog.LogManager.GetLogger(context.ParentType.FullName)
            );
    }
}

I'm perplexed. How do I do what I want?

4

1 回答 1

3

ParentType in the context yields null if the object on the top of the build stack is beeing requested, which would mean that a Logger is requested. I tried a simple scenario with a class having a ctor dependency to a NLog.Logger and it worked perfectly.

c.For<NLog.Logger>().Use(ctx => ctx.ParentType == null ? 
    NLog.LogManager.GetLogger(ctx.BuildStack.Current.ConcreteType.Name) :   
    NLog.LogManager.GetLogger(ctx.ParentType.UnderlyingSystemType.Name));

I had the following dependent class:

public class Service : IService
{
    private readonly NLog.Logger _logger;
    public Service(NLog.Logger logger)
    {
        _logger = logger;
    }
}

which produced a NLog.Logger with the name Service.

If this doesn't work for you I think you need to produce a small repro of the problem.

By the way, you don't need EnrichWith unless you want to wrap the constructed instance with something else or use some data from the constructed instance.

于 2013-07-05T09:24:01.300 回答