比喻我現在在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(); } }