你根据请求主机值注入了一些类吗?我通过Nuget安装了Ninject MVC3 lib。我正在寻找这样的东西:
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();
}
答案 0 :(得分:2)
这有帮助吗?
https://github.com/ninject/ninject/wiki/Contextual-Binding
提到了一个与你正在做的事情类似的例子,但它引用了v1而不是v2
https://github.com/ninject/ninject/wiki/Conventions-Based-Binding
答案 1 :(得分:1)
试试这种方式。
Bind<IMyInterface>().To<XImplementation>().When(ctx => host.StartstWith("x.")).InRequestScope();
Bind<IMyInterface>().To<YImplementation>().When(ctx => host.StartstWith("y.")).InRequestScope();