Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resolve NLog instance with unity container

I have the following class:

public class TestInjection
{
    private ILogger logger;
    public TestInjection(ILogger logger)
    {
        this.logger = logger;
    }

    public void Process()
    {
        try
        {
            int zero = 0;
            int result = 5 / zero;
        }
        catch (DivideByZeroException ex)
        {
            logger.Log(LogLevel.Error, "test message", ex);
            Console.WriteLine("logged message from class");
        }
    }
}

And in my Program.cs I have the code:

IUnityContainer container = new UnityContainer();
container.RegisterType<TestInjection>();

var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", LogManager.GetCurrentClassLogger()) });
myTestClass.Process();

How to resolve LogManager.GetCurrentClassLogger() with the unity container, if the default constructor of the Logger class it's not accessible?

PS: This is my first experience with DI and Unity.

like image 754
Buda Gavril Avatar asked Mar 10 '23 21:03

Buda Gavril


1 Answers

Here is how I've done:

IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger>(
    new InjectionFactory(l => LogManager.GetCurrentClassLogger()));
container.RegisterType<TestInjection>();

var myTestClass = container.Resolve<TestInjection>(
    new ResolverOverride[]
    {
        new ParameterOverride("logger", container.Resolve<ILogger>())
    });
myTestClass.Process();
like image 65
Buda Gavril Avatar answered Mar 25 '23 01:03

Buda Gavril