我想在不同的控制器中使用不同的接口。使用Autofac在兩個控制器中獲得不同的接口
public interface IMessenger {
Id {get; set;}
void Send();
}
我有兩個類實現兩個相同的接口。
public class SmsSender : IMessenger {
public Id {get; set;}
public void Send() {
//logic here
}
}
public class MailSender : IMessenger {
public Id {get; set;}
public void Send() {
//logic here
}
}
兩個控制器:
public class HomeController : Controller {
private readonly IMessenger _messenger;
public HomeController(IMessenger messenger) {
_messenger = messenger;
}
}
public class Home2Controller : Controller {
private readonly IMessenger _messenger;
public HomeController(IMessenger messenger) {
_messenger = messenger;
}
}
Autofaq設置:
builder.RegisterType<MailSender>().As<IMessenger>().InstancePerLifetimeScope();
builder.RegisterType<SmsSender>().As<IMessenger>().InstancePerLifetimeScope();
我怎樣才能得到SmsSender中的HomeController和MailSender在Home2Controller?
您在使用其他IOC容器打開?我相信Ninject具有此功能 –
[依賴注入類型選擇]的可能重複(http://stackoverflow.com/questions/34329203/dependency-injection-type-selection) – NightOwl888
[有關於此主題的完整常見問題。]( http://autofac.readthedocs.io/en/latest/faq/select-by-context.html) –