1. 程式人生 > >.net core中使用autofac進行IOC

.net core中使用autofac進行IOC

display 如果 pes 否則 pub 輕量 splay section 量化

.net Core中自帶DI是非常簡單輕量化的,但是如果批量註冊就得擴展,下面使用反射進行批量註冊的

技術分享圖片
public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!string.IsNullOrEmpty(assemblyName))
            {
                var assembly = Assembly.Load(assemblyName);
                var ts = assembly.GetTypes().ToList();

                
var result = new Dictionary<Type, Type[]>(); foreach (var item in ts.Where(s => !s.IsInterface)) { var interfaceType = item.GetInterfaces(); result.Add(item, interfaceType); } return
result; } return new Dictionary<Type, Type[]>(); }
View Code 技術分享圖片
 1  public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc();
 4             services.Configure<ConnectionOptions>(_configuration.GetSection("
ConnectionStrings")); 5 6 //集中註冊服務 7 foreach (var item in GetClassName("Service")) 8 { 9 foreach (var typeArray in item.Value) 10 { 11 services.AddScoped(typeArray, item.Key); 12 } 13 } 14 }
View Code

下面是將自帶的DI換成AutoFac進行批量DI

(NuGet引入Autofac,Autofac.Configuration,Autofac.Extensions.DependencyInjection)

技術分享圖片
1 public class AutofacModule : Autofac.Module
2     {
3         //重寫Autofac管道Load方法,在這裏註冊註入
4         protected override void Load(ContainerBuilder builder)
5         {
6             //註冊Service中的對象,Service中的類要以Service結尾,否則註冊失敗
7              builder.RegisterAssemblyTypes(Assembly.Load("CoreDemo")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
8         }
9     }
View Code 技術分享圖片
 1 public IServiceProvider ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc();
 4             services.Configure<ConnectionOptions>(_configuration.GetSection("ConnectionStrings"));
 5 
 6             #region 註冊Autofac
 7             //實例化Autofac容器
 8             var builder = new ContainerBuilder();
 9             //將Services中的服務填充到Autofac中
10             builder.Populate(services);
11             //新模塊組件註冊    
12             builder.RegisterModule<AutofacModule>();
13             //創建容器
14             var Container = builder.Build();
15             //Autofac接管.net core內置DI容器 
16             return new AutofacServiceProvider(Container);
17             #endregion
18         }
View Code

.net core中使用autofac進行IOC