My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Log4NetIntegration  
Help integrating Autofac and Log4Net
Autofac2
Updated Dec 20, 2010 by nicholas...@gmail.com

Configure Autofac to inject ILog parameters based on the type of the component being activated.

public class LogInjectionModule : Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Preparing += OnComponentPreparing;
    }

    static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        var t = e.Component.Activator.LimitType;
        e.Parameters = e.Parameters.Union(new[]
        {
            new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), (p, i) => LogManager.GetLogger(t))
        });
    }
}

Note

This approach only works for constructor injection, which is the recommended strategy when using Autofac.

Contribution by Rich Tebb/Bailey Ling:

To that end, I hereby donate a revamped bit of code that instantiates an appropriate log4net ILog instance. The original was for Autofac v1, but this is a reworking for v2. I can't post on the original thread (http://groups.google.com/group/autofac/msg/704f926779cbe8b3) where it belongs, but credits to Bailey Ling for the original idea.

Comment by miha.val...@gmail.com, Sep 26, 2010

For some reason unknown to me, this does not work when you want to inject properties. I have an ActionInvoker? that has a property dependency on ILog and container.InjectProperties? does not set the ILog (actually the AttachToComponentRegistration? is not getting invoked at all). Perhaps by design?

So I solved this by registering the "default" logger for such cases in the Load override.

Comment by project member nicholas...@gmail.com, Dec 20, 2010

Thanks - I've added a note calling out that this implementation does not support property injection.


Sign in to add a comment
Powered by Google Project Hosting