首页 > Web开发 > 详细

.net core中使用autofac进行IOC

时间:2019-03-26 23:38:26      阅读:226      评论:0      收藏:0      [点我收藏+]

.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

原文:https://www.cnblogs.com/LiuNew/p/10604470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!