简体   繁体   中英

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.

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM