zoukankan      html  css  js  c++  java
  • autofac 一个接口多个实现的情况

    比喻我现在在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 "微信支付";
            }
      }

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

    //单独注册
    builder.RegisterType<WxPayService>().Named<IPayService>(typeof(WxPayService).Name);
    builder.RegisterType<AliPayService>().Named<IPayService>(typeof(AliPayService).Name);

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

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

    public class HomeController : Controller
    {
    private IPayService _wxPayService; private IPayService _aliPayService; private IComponentContext _componentContext;//Autofac上下文 //通过构造函数注入Service public HomeController(IComponentContext componentContext) { _componentContext = componentContext; //解释组件 _wxPayService = componentContext.ResolveNamed<IPayService>(typeof(WxPayService).Name); _aliPayService =componentContext.ResolveNamed<IPayService>(typeof(AliPayService).Name); } public IActionResult Index() { ViewBag.wxPay = _wxPayService.Pay(); ViewBag.aliPay = _aliPayService.Pay(); return View(); } }
  • 相关阅读:
    自定义打包工具对应的解析代码
    自定义的打包工具源码
    一种C语言实现面向对象特性的继承,多态
    buffers和cached的区别
    初识rt-thread杂记
    一种多叉树的实现,提供树形结构打印,树转表输出等功能
    关于rtsp的时间戳问题
    一种基于状态机(表)的小组件
    一种基于消息发布-订阅的观察者模式实现
    命令解析类代码重构
  • 原文地址:https://www.cnblogs.com/netcs/p/12889834.html
Copyright © 2011-2022 走看看