.net core2.1 三层中使用Autofac代替原来Ioc

简介: 原文:.net core2.1 三层中使用Autofac代替原来Ioc  首先,现有的三层项目的结构 其中  Repository public interface IPersonRepository { string Eat(); } ...
原文: .net core2.1 三层中使用Autofac代替原来Ioc

  首先,现有的三层项目的结构

其中  Repository

 public interface IPersonRepository
    {
         string Eat();
    }
public class PersonRepository : IPersonRepository
    {
        public string Eat()
        {
            return "吃饭";
        }
    }

 Service

public interface IPersonService
    {
        string Eat();
    }
 public class PersonService : IPersonService
    {
       private  IPersonRepository _personRespository;
        //通过构造函数注入 repository
        public  PersonService(IPersonRepository personRespository)
        {
          _personRespository = personRespository;
        }
        public string Eat()
        {
            return  _personRespository.Eat();
        }
    }

 

一、安装Autofac

      nuget上安装Autofac

 

二、替换内置的DI框架

    将Startup.cs中的ConfigureServices返回类型改为IServiceProvider,然后新起一个方法RegisterAutofac把创建容器的代码放到其中,然后建一个AutofacConfig 类来存放具体的注入代码,避免

  Startup.cs文件代码过多混乱。

    

 public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            return RegisterAutofac(services);//注册Autofac
        }
        private IServiceProvider RegisterAutofac(IServiceCollection services)
        {
            //实例化Autofac容器
            var builder = new ContainerBuilder();
            builder.Populate(services);
            //Autofac注册对象        
             AutofacConfig.RegisterObj(builder);
            var Container = builder.Build();
            //第三方IOC接管 core内置DI容器 
            return new AutofacServiceProvider(Container);
        }
 public class AutofacConfig
    {
        public static void RegisterObj(ContainerBuilder builder)
        {
            //注册Service中的组件,Service中的类要以Service结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            //注册Repository中的组件,Repository中的类要以Repository结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
        }
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
    }

此时Autofac基本使用已经配好了。

三、测试效果

        修改HomeController 实现注入Service

 public class HomeController : Controller
    {
        private IPersonService _personService;
      
        //通过构造函数注入Service
        public HomeController(IPersonService personService)
        {
            _personService = personService;
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            return View();
        }
}

页面结果:

四、一个接口多个实现的情况

   比喻我现在在Service 中建三个类,IPayService, WxPayService,AliPayService,其中WxPayService,AliPayService都实现接口IPayService。

 public interface IPayService
    {
        string Pay();
    }
public class AliPayService : IPayService
    {
        public string Pay()
        {
            return "支付宝支付";
        }
    }
 public class WxPayService : IPayService
    {
        public string Pay()
        {
            return "微信支付";
        }
    }

  先试一下结果,修改HomeController

 public class HomeController : Controller
    {
        private IPersonService _personService;
        private IPayService _payService;
      
        //通过构造函数注入Service
        public HomeController(IPersonService personService,IPayService payService)
        {
            _personService = personService;
            _payService = payService;
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            ViewBag.pay = _payService.Pay();
            return View();
        }
    }

  View

@{
    ViewData["Title"] = "Home Page";
}
@ViewBag.eat <br />
@ViewBag.pay

输出页面:

    最后得到的是微信支付,因为两个对象实现一个接口的时候,注册时后面注册的会覆盖前面注册的。如果我想得到支付宝支付要怎么做呢?

 我们可以用另外一种注册方式RegisterType,修改注册方式AutofacConfig.cs。

 

public static void RegisterObj(ContainerBuilder builder)
        {
            //注册Service中的组件,Service中的类要以Service结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Service")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
            //注册Repository中的组件,Repository中的类要以Repository结尾,否则注册失败
            builder.RegisterAssemblyTypes(GetAssemblyByName("WXL.Repository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
            //单独注册
            builder.RegisterType<WxPayService>().Named<IPayService>(typeof(WxPayService).Name);
            builder.RegisterType<AliPayService>().Named<IPayService>(typeof(AliPayService).Name);
        }
        /// <summary>
        /// 根据程序集名称获取程序集
        /// </summary>
        /// <param name="AssemblyName">程序集名称</param>
        /// <returns></returns>
        public static Assembly GetAssemblyByName(String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }

用Named区分两个组件的不同,后面的typeof(WxPayService).Name 是任意字符串,这里直接用这个类名作标识,方便取出来时也是用这个名字,不易忘记。

然后就是取出对应的组件了,取的时候用Autofac的 上下文(IComponentContext) ,修改HomeController

 public class HomeController : Controller
    {
        private IPersonService _personService;
        private IPayService _wxPayService;
        private IPayService _aliPayService;
        private IComponentContext _componentContext;//Autofac上下文
        //通过构造函数注入Service
        public HomeController(IPersonService personService, IComponentContext componentContext)
        {
            _personService = personService;
            _componentContext = componentContext;
            //解释组件
            _wxPayService = componentContext.ResolveNamed<IPayService>(typeof(WxPayService).Name);
            _aliPayService =componentContext.ResolveNamed<IPayService>(typeof(AliPayService).Name);
        }
        public IActionResult Index()
        {
            ViewBag.eat = _personService.Eat();
            ViewBag.wxPay = _wxPayService.Pay();
            ViewBag.aliPay = _aliPayService.Pay();
            return View();
        }
    }

 Index View:

@{
    ViewData["Title"] = "Home Page";
}
@ViewBag.eat <br />
@ViewBag.wxPay <br />
@ViewBag.aliPay

结果:

 

完成。

 

    

 

目录
相关文章
|
7月前
|
容器
.net core Autofac IOC 容器的简单使用
## 书接上回,介绍了[.net core 读取配置文件的几种方式](https://developer.aliyun.com/article/1363340?spm=a2c6h.13148508.setting.14.21764f0ehMR1KI ".net core 读取配置文件的几种方式"),本文学习Autofac的同时再次增加一种读取配置文件的方法。 ## 本文介绍Auofac,一个优秀的.NET IOC框架 ## 源码地址:https://github.com/autofac/Autofac # 1、打开NuGet包管理器安装Autofac.Extensions.Dependenc
46 0
|
8月前
|
容器
.NET Core - Autofac增强容器能力
.NET Core - Autofac增强容器能力
|
API
.net core工具组件系列之Autofac—— 第二篇:Autofac的3种依赖注入方式(构造函数注入、属性注入和方法注入),以及在过滤器里面实现依赖注入
本篇文章接前一篇,建议可以先看前篇文章,再看本文,会有更好的效果。前一篇跳转链接:https://www.cnblogs.com/weskynet/p/15046999.html
425 0
.net core工具组件系列之Autofac—— 第二篇:Autofac的3种依赖注入方式(构造函数注入、属性注入和方法注入),以及在过滤器里面实现依赖注入
|
7月前
|
开发框架 前端开发 .NET
ASP.NET Core 使用Autofac
ASP.NET Core 使用Autofac
59 0
ASP.NET Core 使用Autofac
|
8月前
|
容器
.NET Core Autofac增强容器能力
本节学习利用第三方框架Autofac来增强容器能力,并引入面向切面(AOP)编程的概念。
|
9月前
.net 6 中使用Autofac
.net 6 中使用Autofac
151 0
|
XML 开发框架 前端开发
在ASP.Net Core下,Autofac实现自动注入
在ASP.Net Core下,Autofac实现自动注入
199 0
在ASP.Net Core下,Autofac实现自动注入
|
前端开发 C# 图形学
【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入
前言:在C/S架构上,WPF无疑已经是“桌面一霸”了。在.NET生态环境中,很多小伙伴还在使用Winform开发C/S架构的桌面应用。但是WPF也有很多年的历史了,并且基于MVVM的开发模式,受到了很多开发者的喜爱。
568 0
【.NET6+WPF】WPF使用prism框架+Unity IOC容器实现MVVM双向绑定和依赖注入
|
JSON API 数据格式
.net core工具组件系列之Autofac—— 第一篇:Autofac系列Autofac的几种常见注册方式、生命周期和AOP
使用Autofac进行服务注册实践:新建三个项目,分别是webapi项目 Wesky.Core.Autofac以及两个类库项目 Wesky.Core.Interface和Wesky.Core.Service。在Webapi项目下,引用Autofac的三个包:Autofac、Autofac.Configuration和Autofac.Extensions.DependencyInjection 。
1001 1
.net core工具组件系列之Autofac—— 第一篇:Autofac系列Autofac的几种常见注册方式、生命周期和AOP
|
容器
五:.net core(.NET 6)使用Autofac实现依赖注入
Autofac的简单使用:由于将来可能引用很多包,为了保持统一队形,我们再新建一个类库项目Wsk.Core.Package,当做包的引用集合:
543 0
五:.net core(.NET 6)使用Autofac实现依赖注入