3

我对 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>(); }
...

问题是此时 HttpContext.Current 为空。所以我的问题是如何在 NinjectWebCommon.RegisterServices 中获取 HttpContext 数据。任何关于我可能在 Ninject 上出错的方向也将不胜感激。

谢谢

4

1 回答 1

6

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

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

这意味着,每次ICustomerRepository调用 时,NInject 都会使用 current 运行该方法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);
于 2013-08-01T22:00:38.020 回答