Ali_Nass
Ali_Nass

Reputation: 928

Is there a way to Resolve log4net using Unity without calling ILog in the constructor?

So the way I usually do it (with DI) is to add the extension to my container:

unityContainer.AddNewExtension<Log4NetExtension>();

and then at the constructor of the class where I need to call the logger I use something like this:

public class test
{
    private ILog logger;
    public test (ILog logger)
    {
        this.logger =logger;
    }
}

Now my problem is, in one of my classes, I don't want to pass anything to the constructor and I was wondering how can I assign my logger (since im using unity I thought of calling resolve but it's not working)

public class test
{
    private ILog logger;

    public test()
    {
        logger = unityContainer.Resolve<ILog>(); //I edited this for simplicity
    }
}

Error is something like the container didn't know how to resolve ILog.

EDIT:

The class that didn't let me pass anything through its constructor is a Job (implements IJob) class, in the end I ended up using a job listener instead of logging in each job.

Some tips if you still want to pass something for the constructor is by implementation a Job Factory which should help you inject parameters. And I saw a nuget you can add to help you with Quartz integration with Unity.

Upvotes: 1

Views: 960

Answers (2)

Haukinger
Haukinger

Reputation: 10863

You can use property injection:

public class test
{
    [Dependency]
    public ILog Logger { get; set; }

    public test()
    {
    }
}

Two drawbacks, though:

  1. the logger's a public writable property now, so anyone could technically use or overwrite your logger
  2. property injection is meant for optional dependencies, so you might be confusing others who look at the class

Upvotes: 0

Bernard Vander Beken
Bernard Vander Beken

Reputation: 5056

Log4net allows you create a logger using a name in your class, no need to pass it via a constructor.

Add this as a class member

private static readonly log4net.ILog logger = log4net.LogManager.GetLogger("MyAppLog");

Of course, this does not use your DIContainer.

Upvotes: 1

Related Questions