我需要在ASP核心3.0中使用此AutoFac
当我在启动时使用此代码时:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
return services.BuildAutofacServiceProvider();
}
它向我显示此错误:
“不支持ConfigureServices返回System.IServiceProvider。”
然后我通过以下方式更改program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
但是没有解决。
这是BuildAutofacServiceProvider()
代码:
public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services)
{
var ContainerBuilder = new ContainerBuilder();
ContainerBuilder.Populate(services);
ContainerBuilder.AddService();
var container = ContainerBuilder.Build();
return new AutofacServiceProvider(container);
}
我该如何解决这个问题?
答案 0 :(得分:9)
启动语法已更改,可以为ASP.NET Core 3.0+配置Autofac
除了在主机生成器上使用以下内容
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
在Startup
中执行以下格式
public void ConfigureServices(IServiceCollection services) {
//... normal registration here
// Add services to the collection. Don't build or return
// any IServiceProvider or the ConfigureContainer method
// won't get called.
services.AddControllers();
}
// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you. If you
// need a reference to the container, you need to use the
// "Without ConfigureContainer" mechanism shown later.
public void ConfigureContainer(ContainerBuilder builder) {
//configure auto fac here
builder.AddService();
//...
}
ASP.NET Core 3.0及更高版本的参考文献Autofac documentation
答案 1 :(得分:1)
您可以使用Host
代替Program.cs中的WebHost
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
在这种情况下,以下代码有效
public IServiceProvider ConfigureServices(IServiceCollection services)
{
...
var builder = new ContainerBuilder();
builder.Populate(services);
var container = builder.Build();
return new AutofacServiceProvider(container);
}