Ninject与HttpContext.Current上的MVC4条件绑定

Cro*_*rob 3 asp.net-mvc ninject ninject.web.mvc asp.net-mvc-4

我对Ninject不太熟悉,所以我可能在这里有一个完全错误的概念,但这就是我想要做的.我有一个多租户Web应用程序,并希望注入一个不同的类对象,具体取决于用于访问我的网站的URL.

虽然也许我可以在绑定中使用.When(),但你得到了这个想法:

    private static void RegisterServices(IKernel kernel)
    {
        var currentTenant = TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower());
        if (currentTenant.Foldername == "insideeu")
        { kernel.Bind<ICustomerRepository>().To<AXCustomerRepository>(); }
        else
        { kernel.Bind<ICustomerRepository>().To<CustomerRepository>(); }
...
Run Code Online (Sandbox Code Playgroud)

问题是此时HttpContext.Current为null.所以我的问题是如何在NinjectWebCommon.RegisterServices中获取HttpContext数据.我对Ninject可能出错的任何方向都会非常感激.

谢谢

McG*_*gle 6

问题是你的绑定在编译时解决了; 而你需要它在运行时解决每个请求.为此,请使用ToMethod:

Bind<ICustomerRepository>().ToMethod(context => 
    TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower()).Foldername == "insideeu" 
    ? new AXCustomerRepository() : new CustomerRepository());
Run Code Online (Sandbox Code Playgroud)

这意味着,每次ICustomerRepository调用时,NInject都将使用当前运行方法HttpContext,并实例化相应的实现.

请注意,您还可以使用Get解析类型而不是特定构造函数:

Bind<ICustomerRepository>().ToMethod(context => 
    TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower())
        .Foldername == "insideeu" ?  
            context.Kernel.Get<AXCustomerRepository>() : context.Kernel.Get<CustomerRepository>()
    as ICustomerRepository);
Run Code Online (Sandbox Code Playgroud)