我正在尝试将结构图注入.net core 3.0 Web API,但是连续不断地在Program.cs类中收到错误消息。我还没有找到任何与结构图有关的解决方案,每个人都在讨论Autofac
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
我的启动课程是
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var container = new Container();
container.Configure(config =>
{
config.AddRegistry(new CustomRegistry());
config.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
如果您有任何建议,请告诉我。 谢谢您的帮助!
答案 0 :(得分:1)
Program.cs在代码下添加AutofacServiceProviderFactory
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseServiceProviderFactory(new AutofacServiceProviderFactory());
然后在StartUp.cs中添加ConfigureContainer
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(typeof(Program).Assembly).
Where(x => x.Name.EndsWith("service", StringComparison.OrdinalIgnoreCase)).AsImplementedInterfaces();
builder.RegisterDynamicProxy();
}
在dotnet core 3.0中更改ioc方式