I know that this question is requesting how to use two libraries, integrated into one .Net project, but after a lot of searching and article reading, I can't find anything specifically useful. Regardless, since setting up a logging dependency is a bit of a special case in ASP.Net Core, I think it's a good sample case to request on how to setup Autofac with a dependency example in an ASP.Net Core 3.0 Web API project.
I have a brand new, ASP.Net Core 3.0 Web API project (from the Visual Studio 2019 templates) and I need to add Autofac and NLog.
Autofac has documentation on setting itself up with ASP.Net Core 3.0, but since their examples use a standard Web project (complete with Razor and MVC setup), the structure of the project template is rather different than the basic ASP.Net Web API project. I can't figure out how to translate the web project information to my Web API project.
I think the majority of my problem is trying setup Autofac but since the first injected component I want to setup is a logger engine for ASP.Net Core, it seemed prudent to try and get the two to work together before trying to setup other components that I might write and which should be simpler to implement.
If anyone can provide some basic examples from within a brand new ASP.Net Core 3.0 Web API project showing how to properly setup Autofac and NLog, that would be helpful. I'm not doing anything atypical or fancy and at the moment, my project is a brand new project created from the templates provided by Visual Studio 2019.
In your Program.cs you should add the .UseServiceProviderFactory(new AutofacServiceProviderFactory())
method for Autofac and the .UseNLog()
and NLogBuilder.ConfigureNLog("nlog.config")
for nlog.
public class Program
{
public static void Main(string[] args)
{
NLogBuilder.ConfigureNLog("nlog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
The UseNLog
method will register things in the internal dependency injection and Autofac will use it. You don't have to do anything for NLog with Autofac thanks to this method.
In the startup.cs file you should add a ConfigureContainer
method to configure Autofac but you don't have to do anything for NLog.
public void ConfigureContainer(ContainerBuilder builder)
{
// do whatever you want with Autofac
// you don't have to register anything for NLog
// the `UseNLog` method will register everything for you
builder.RegisterType<Service>().As<IService>();
}