Autofac 3种常见注入IOC 以及生命周期 以及Net6 简单注入
.Net6 简单使用构造函数注入
using System.Reflection; using Autofac; using Autofac.Extensions.DependencyInjection; //直接引入该Nuget package即可 using mywebapi.service.Application; using mywebapi.service.Application.Contracts; using System.Linq; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); //AutofacServiceProviderFactory builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(c => { //注入单个 // c.RegisterType<TestService>().AsImplementedInterfaces(); //注入单个 // c.RegisterType<TestService>().As<ITestService>(); //批量注入 Assembly assembly = Assembly.Load("mywebapi.service.Application"); c.RegisterAssemblyTypes(assembly).AsImplementedInterfaces(); }); 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();
如有疑问或者错误的地方,请跟帖,本人会第一时间答复以及相互学习,谢谢!个人会不断的上传自己的学习心得!
好了今天就先到这里,下次有时间再更新,如果存在不合理的地方,欢迎大家多多指教留言!!!