I have a ASP.NET Core app using Autofac as DI container. I'm also using built-in logging mechanism that provides ILogger<> dependency. Now I'd like to register it in Autofac. How?
To create logs, use an ILogger<TCategoryName> object. In a web app or hosted service, get an ILogger from dependency injection (DI). In non-host console apps, use the LoggerFactory to create an ILogger. The following ASP.NET Core example creates a logger with TodoApiSample.Pages.AboutModel as the category.
Creating a logging provider is relatively easy in ASP.NET Core as you can build the functionality around methods that are contained in the ILogger and ILoggerProvider interfaces. We will have a look at creating and implementing a logging provider so it we can log to a table in a SQL Server database.
ASP.NET Core doesn't include a logging provider for writing logs to files. To write logs to files from an ASP.NET Core app, consider using a third-party logging provider.
We can use ILogger or ILoggerFactory anywhere in an application using ASP.NET Core DI (Dependency Injection). Consider the following example of HomeController : In the above example, the ILogger<HomeController> parameter is included in the constructor. ASP.NET Core DI will pass the ILogger instance, which can be used to log in the Index () ...
As already stated, when you use the official autofac-integration for asp.net-core you don't need to do anything. If you still want to do it manually, which is legit, you could do the following in the ConfigureContainer
method.
public void ConfigureContainer(ContainerBuilder builder)
{
// ... more registrations
builder.RegisterInstance(new LoggerFactory())
.As<ILoggerFactory>();
builder.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>))
.SingleInstance();
}
Keep in mind that their is no specific logging-provider added.
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