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(); } }
原文地址:https://www.cnblogs.com/netcs/p/12889834.html