0

「管理者がこのインスタンスを注入する領域内のコントローラーに IService を注入するとき」というバインディングを作成する方法はありますか?

Admin には、同じサービスを使用する可能性のある多数のコントローラーがあります。コントローラーごとにバインディングを作成することもできますが、別のコントローラーが同じサービスで導入される可能性があり、開発者は管理者 (他のエリアまたはエリア外とは異なるサービス実装のセットを使用する) 用に特別に接続するのを忘れる可能性があります。

// this is the default
kernel.Bind<ICategorizationRepository<DirectoryCategory>>().To<CachedJsonCategorizationProvider<DirectoryCategory>>().InRequestScope();

// Admin bindings use noncaching repositories
kernel.Bind<ICategorizationRepository<DirectoryCategory>>().To<JsonCategorizationProvider<DirectoryCategory>>().WhenInjectedInto<Areas.Admin.Controllers.DirectoryCategorizationController>().InRequestScope();
kernel.Bind<ICategorizationRepository<DirectoryCategory>>().To<JsonCategorizationProvider<DirectoryCategory>>().WhenInjectedInto<Areas.Admin.Controllers.DirectoryEntryController>().InRequestScope();
// .. new controller that uses ICategorizationRepo might be created but the developer forgets to wire it up to the non caching repository - so the default one will be used, which is undesirable

私が言いたいのは、管理領域内の何かに注入するときは、これを使用してください...

4

1 に答える 1

2

独自の when 条件を記述します。

.When(request => request.Target.Member.ReflectedType is a controller in the area namespace)

@mareによる更新:

どのように解決したかの詳細で回答を更新します。あなたは私を正しい方向に向けてくれました。あなたの答えから正しい解決策にたどり着くのは簡単でした。これは私がやったことです:

// custom when condition
Func<IRequest, bool> adminAreaRequest = new Func<IRequest, bool>(r => r.Target.Member.ReflectedType.FullName.Contains("Areas.Admin"));

kernel.Bind<ICategorizationRepository<DirectoryCategory>>).To<JsonCategorizationProvider<DirectoryCategory>>().When(adminAreaRequest).InRequestScope();

すべてのコントローラーが xyz.Areas.Admin 名前空間にあるため、FullName には常にその文字列が含まれます。別のカスタム リクエストが必要な場合は、このリクエストと同じように簡単に作成できます。

于 2012-05-20T21:09:54.200 に答える