c# - 在 asp.net core 2.2 中使用 autofac
问题描述
我正在尝试将最新的 Autofac 与 asp.net core 2.2 项目一起使用。但是 autofac 的文档似乎已经过时了。我正在尝试在没有 ConfigureContainer 的情况下使用 autofac:
// ConfigureServices is where you register dependencies. This gets
// called by the runtime before the Configure method, below.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add services to the collection.
services.AddMvc();
// Create the container builder.
var builder = new ContainerBuilder();
// Register dependencies, populate the services from
// the collection, and build the container.
//
// Note that Populate is basically a foreach to add things
// into Autofac that are in the collection. If you register
// things in Autofac BEFORE Populate then the stuff in the
// ServiceCollection can override those things; if you register
// AFTER Populate those registrations can override things
// in the ServiceCollection. Mix and match as needed.
builder.Populate(services);
builder.RegisterType<MyType>().As<IMyType>();
this.ApplicationContainer = builder.Build();
// Create the IServiceProvider based on the container.
return new AutofacServiceProvider(this.ApplicationContainer);
}
但是在 asp.net core 2.2 中的 ConfigureServices 方法签名是不同的
public void ConfigureServices(IServiceCollection services)
{
}
没有返回类型。任何人都知道如何在 asp.net core 2.2 中使用 autofac?
解决方案
你需要使用这个包:
Autofac.Extensions.DependencyInjection
在您的 program.cs 中,只需使用以下代码行:
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services => services.AddAutofac());
}
在您的 startup.cs 中,创建一个名为
public void ConfigureContainer(ContainerBuilder builder)
{
}
并使用“builder”来注册你想要的任何东西。Autofac 会自己找到这个方法。
你不需要再打电话builder.Build()
了。
为了执行带有注入值的重复代码,您需要添加以下备注:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHostedService<MyHostedService>();
...
}
public class MyHostedService : IHostedService
{
private Timer _timer;
private IInjectedService _myInjectedService;
public MyHostedService(IServiceProvider services)
{
var scope = services.CreateScope();
_myInjectedService = scope.ServiceProvider.GetRequiredService<IInjectedService>();
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
private async void DoWork(object state)
{
_myInjectedService.DoStuff();
}
}