(1)添加Autofac.Extensions.DependencyInjection引用?
(2)Program类中添加如下代码
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())//Step 1:容器替换 ? ? .ConfigureContainer<ContainerBuilder>(builder => { ? ? //服务层程序集命名空间 ? ? Assembly userService = Assembly.Load("Demo.UserService"); ? ? //自动注入 ? ? builder.RegisterAssemblyTypes(userService) ? ? ? ? .Where(t => t.Name.EndsWith("Service")||t.Name.EndsWith("Repository")) ? ? ? ? .AsImplementedInterfaces().SingleInstance(); });
Program类所有代码:
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())//Step 1:容器替换
.ConfigureContainer<ContainerBuilder>(builder =>
{
//服务层程序集命名空间
Assembly userService = Assembly.Load("Demo.UserService");
//自动注入
builder.RegisterAssemblyTypes(userService)
.Where(t => t.Name.EndsWith("Service")||t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().SingleInstance();
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
|