简体   繁体   中英

autofac wiring Type to my logger

I have a logger as follows:

public class Logger : ILogger
{ 
    private ILogger _logger;

    public Logger(Type type)
    { 
        _logger =  LogManager.CreateLogger(type);
    }
     .... removed

I am trying to build a log module:

public class LogModule : Autofac.Module
{       
    protected override void Load(ContainerBuilder builder)
    {
        const string propertyNameKey = "Autofac.AutowiringPropertyInjector.InstanceType";


        builder.RegisterType<Logger>().As<ILogger>();
        base.Load(builder);
    }
}

I have to find and inject the type into the Logger , something like this question is asking, but that question does property injection, i need ctor injection.

How can I get contextual logging, ie log per Type?

You can use the Preparing of the registration object. This code is taken from the autofac page .

public class LoggingModule : Autofac.Module
{

    private static void InjectLoggerProperties(object instance)
    {
        var instanceType = instance.GetType();

        // Get all the injectable properties to set.
        // If you wanted to ensure the properties were only UNSET properties,
        // here's where you'd do it.
        var properties = instanceType
          .GetProperties(BindingFlags.Public | BindingFlags.Instance)
          .Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);

        // Set the properties located.
        foreach (var propToSet in properties)
        {
            propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
        }
    }

    private static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        e.Parameters = e.Parameters.Union(
          new[]
          {
             new ResolvedParameter(
                (p, i) => p.ParameterType == typeof(ILog),
                (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
             ),
          });
    }

    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        // Handle constructor parameters.
        registration.Preparing += OnComponentPreparing;

        // Handle properties.
        registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
    }
}

This code:

private static void OnComponentPreparing(object sender, PreparingEventArgs e)
{
    e.Parameters = e.Parameters.Union(
      new[]
      {
         new ResolvedParameter(
            (p, i) => p.ParameterType == typeof(ILog),
            (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
         ),
      });
}

injects a new logger (using the class name) to the CTOR.

class ClassA 
{
    ... 
    ClassA(ILog logger) => this.logger = logger; // logger was created by Autofac via LogManager.GetLogger("ClassA")
}

Hope that is the thing you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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