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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With