Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4net and Unity register

I'm trying to configure Unity to inject an ILog into my classes, where the type/name in LogManager.CreateLogger() is set as the class where ILog is being injected into.

Here is a similar question, but for Structure Map

like image 673
Karsten Avatar asked Nov 13 '22 22:11

Karsten


1 Answers

I know this answer is very late, but I've recently had this issue.

There is now a NuGet package, UnityLog4NetExtension, that registers the log4net.ILog interface and some Unity build strategies that allows you to just inject an ILog interface and have Unity create it using the class that it is being injected in to.

The code is also available via GitHub.

For example:

Add the extension to the unity container, before you need to inject ILog instancies. I've done this in the bootstrapper.

//add the extension to the unity container 
container.AddNewExtension<Log4NetExtension>();

Then, just inject the ILog interface and it will work

public class MyClass
{ 
    private readonly ILog _logger;

    public MyClass(ILog loggerForMyClass)
    {
        _logger = loggerForMyClass;
    }
}

This code works just as if I'd written _logger = LogManager.GetLogger(typeof(MyClass))

like image 60
Grhm Avatar answered Dec 06 '22 05:12

Grhm