I'm working with a project which utilizes Simple Injector as dependency injector. On the other hand, this project uses Microsoft.Extensions.Logging in order to log the events that occurs in certain classes.
My technical issue is pretty simple to explain.
I want to register in my DI the ILogger independently of the class T which is being invoked, but I DO NEED to do it from my ILoggerFactory.CreateLogger<T>()
method because this gets the logger configuration using Microsoft.Extensions.Configuration
.
I need to use something like this in order to instance my logger:
private Microsoft.Extensions.Logging.ILogger CreateLogger<T>()
{
var factory = this.ResolveService<ILoggerFactory>();
var logger = factory.CreateLogger<T>();
return logger;
}
I could achieve the injection by doing:
Container.Register(typeof(ILogger<>), typeof(Logger<>));
And this allows us to resolve something like:
public class SomeApiController : ApiController
{
public SomeApiController(ILogger<SomeApiController> logger)
{
//logger is well instantiated, but doesn't got the configuration
logger.LogInformation("test log.");
}
}
But as I said, this does it without passing through the configuration obtained from the Microsoft.Extensions.Logging.ILoggerFactory
class, so this isn't useful.
Is there a way to register
ILogger<T>
by using myCreateLogger<T>
?
The way to do this with Simple Injector is by specifying a generic proxy class that delegates the call to the
ILoggerFactory
.This however causes a problem when using Microsoft.Extensions.Logging, because it's
ILogger<T>
abstraction is one big Interface Segregation Principle violation. ISP violations are problematic, because they make it muc harder to create (among other things) proxy classes. But you should refrain from using that abstraction directly in your application components any way, as prescribed by the Dependency Inversion Principle.Since abstractions should be defined by the application itself, this basically means you need to define your own logger abstraction and on top of that you build an adapter, much like described here. You can simply derive your generic adapter from the described
MicrosoftLoggingAdapter
as follows:Using this generic adapter, you can configure Simple Injector as follows:
In case creating your own abstraction is not (yet) an option, your second best bet is to override Simple Injector's dependency injection behavior, with the following Microsoft.Extensions.Logging-specific class:
You can replace the original behavior as follows:
Based on Steven's solution, I post my answer to help anyone else:
As you can see, my solution is using Serilog as a provider for logging in
Microsoft.Extensions.Logging
.Hope it helps!