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 が null であることです。私の質問は、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 が現在の を使用してメソッドを実行し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 に答える