Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AutoFac without constructor injection

I am trying to use AutoFac and all the examples show it using constructor injection which is a suggested practice. That's ok, but I want to know how to use it where constructor injection is not possible. For example, I want to use NLogger in my app.

Registration happens like so:

builder.RegisterType<NLogger>().As<ILogger>().SingleInstance();

How would I use NLogger without doing like this:

public class ProductService : IProductService
{
    private ILogger _logger;
    public ProductService(ILogger logger)
    {
        this._logger = logger;
    }
 }

Any help is greatly appreciated.

Regards.

like image 339
Codehelp Avatar asked Sep 29 '26 13:09

Codehelp


1 Answers

You can use Property Injection.

In your class you can have

public class MyClass
{
    public ILogger Logger { get; set; }
}

and map with

builder.Register(c => new MyClass { Logger = c.Resolve<ILogger>() });

Constructor injection is the way to go in 99% of cases though.


If you just want to get an instance you need to call

var logger = container.Resolve<ILogger>();

Where container is your AutoFac container - this could be pulled from a global variable - in ASP.NET MVC (if you happen to be using that) you can do this by calling

var logger = DependencyResolver.Current.GetService<ILogger>();
like image 154
dav_i Avatar answered Oct 01 '26 03:10

dav_i



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!