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(); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM