Hod根據請求主機值注入一些類嗎?我通過Nuget安裝了Ninject MVC3庫。我在尋找這樣的事情:ASP.NET MVC3 Ninject有條件注入
private static void RegisterServices(IKernel kernel)
{
var host = get host from request;
if (host.StartstWith("x."))
{
kernel.Bind<IMyInterface>().To<XImplementation>().InRequestScope();
}
else if (host.StartstWith("y."))
{
kernel.Bind<IMyInterface>().To<YImplementation>().InRequestScope();
}
}
編輯:剛發現this answer ..有任何其他方式比工廠?就像我上面的「僞」例子中的那個一樣?
解決方案:
private static void RegisterServices(IKernel kernel)
{
var host = HttpContext.Current.Request.Headers["host"].ToLower();
kernel.Bind<IMyInterface>().To<XImplementation>().When(ctx => host.StartsWith("x.")).InRequestScope();
kernel.Bind<IMyInterface>().To<YImplementation>().When(ctx => host.StartsWith("y.")).InRequestScope();
}
沒辦法,你應該每個請求進行登記。搜索Mark Seemann RRR模式 – 2012-01-15 00:32:03
如果條件結構不足,可以使用ToMethod,ToProvider或構建您自己的工廠。一般來說,有條件的方法應該是你的第一停靠點 - 請參閱@Simon Halsey的回答 – 2012-01-15 00:33:58
@RubenBartelink如果我刪除.InRequestScope(),在使用To時還有什麼問題?是使用工廠更好的乳清?如果這是爲什麼如此? – redman 2012-01-15 11:17:10