Reputation: 33272
In my legacy (well 'traditional') project I was addicted to NInject kernel and Log4Net and I used to do for the log something like this:
kernel.Bind<ILog>().ToMethod((ctx) =>
{
return LogManager.GetLogger(ctx.Request.Target.Member.DeclaringType);
});
that is, I bind the log factory to a function, and that function is able to auto wire the current type creating a Log for the current type. In the ASP.NET configuration I found a way to bind a service to a factory function, but that function will not receive any context information to understand the context the object is needed. Is it possible to emulate the same behavior I had with NInject in some way?
Upvotes: 0
Views: 681
Reputation: 36736
In ASP.NET Core logging and dependency injection are built right into the framework. So you can take a constructor dependency on ILogger of T where T is the type of your class where the logger will be injected.
ie
public class HomeController
{
public HomeController(ILogger<HomeController> logger)
{
_log = logger;
}
private readonly ILogger _log;
}
You can use various logging libraries, but log4net is not commonly used in asp.net core, serilog seems to be the latest favorite. See the list of 3rd party loggers in the logging documentation for asp.net core
Similarly DI is built right in but it is also possible to replace it with 3rd party DI libraries as shown in the section on "Default service container replacement. Autofac seems to be more popular these days than ninject.
Upvotes: 1