通过本文你可以获得如何用 autofac 替换 .NET CORE(2.1,3.1) 默认 IOC 容器。
生命周期说明
-
每个依赖一个实例(Instance Per Dependency) (默认) ----InstancePerDependency()
-
单一实例(Single Instance) 单例 ----SingleInstance()
-
每个生命周期作用域一个实例(Instance Per Lifetime Scope)----InstancePerLifetimeScope()
-
每个匹配的生命周期作用域一个实例(Instance Per Matching Lifetime Scope)----InstancePerMatchingLifetimeScope()
-
每个请求一个实例(Instance Per Request) asp.net web请求----InstancePerRequest()
-
每次被拥有一个实例(Instance Per Owned) ----InstancePerOwned()
注册方式
示例代码说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| var builder = new ContainerBuilder();
builder.RegisterType<ConsoleLogger>().As<ILogger>();
builder.RegisterType<ConsoleLogger>().AsImplementedInterfaces();
var output = new StringWriter(); builder.RegisterInstance(output).As<TextWriter>();
builder.Register(c =new ConfigReader("mysection")).As<IConfigReader>();
var service = scope.Resolve<IConfigReader>( new NamedParameter("section", "mysection"));
builder.RegisterType<ConsoleLogger>();
builder.RegisterType<MyComponent>() .UsingConstructor(typeof(ILogger), typeof(IConfigReader));
builder.RegisterInstance(MySingleton.Instance).ExternallyOwned();
builder.RegisterType<CallLogger>().As<ILogger>().As<ICallInterceptor>();
builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(GetAssembly("MyApp.Repository")).AsImplementedInterfaces();
var rootcontainer = builder.Build();
using(var scope = rootcontainer.BeginLifetimeScope()) { var reader = scope.Resolve<IConfigReader>(); }
|
在 ASP.NET CORE 2.1
中的使用
.NET CORE 2.2 和 3.1 对 Autofac 的初始化方式不一样,需要注意下,建议使用 3.1。
需要安装一下的库:
注册策略:Module
在不同层中定义一个 ModuleRegister 类,用于注册类型
IocPolicy.cs
1 2 3 4 5 6 7 8 9 10
| public class IocPolicy : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().SingleInstance(); } }
|
接管默认 IoC 引擎
需要修改 Startup.cs,需要调整 ConfigServices 方法签名,以让 autofac 接管 ioc
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public static IContainer AutofacContainer; public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); #region >>AutoFac 1/2 ContainerBuilder builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule<Application.IocPolicy>(); builder.RegisterModule<Domain.IocPolicy>(); AutofacContainer = builder.Build(); return new AutofacServiceProvider(AutofacContainer); #endregion }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); #region >>AutoFac 2/2 appLifetime.ApplicationStopped.Register(() => { AutofacContainer.Dispose(); }); #endregion }
|
在 ASP.NET CORE 3.1
中的使用
这里跟 core 2.2不一样,更加偏向于默认的 IoC 容器了,也方便了不少。
需要安装以下的库:
类型注册
在不同层中定义一个 ModuleRegister 类,用于注册类型
IocPolicy.cs
1 2 3 4 5 6 7 8 9 10
| public static class IocPolicy { public static void RegisterApplication(this ContainerBuilder builder) { builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().SingleInstance(); } }
|
接管默认 IoC 引擎
需要修改 Startup.cs,需要调整 ConfigServices 方法签名,以让 autofac 接管 ioc
1 2 3 4 5 6 7 8 9
|
public void ConfigureContainer(ContainerBuilder builder) { #region >>AutoFac builder.RegisterApplication(); builder.RegisterDomain(); #endregion }
|
Program.cs
1 2 3 4 5 6 7
| public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
|