2012-05-20 20 views
0

有沒有辦法做一個綁定,會說「當注入IService到區域內的任何控制器管理員注入此實例」?用Ninject注入區域內的控制器

我們在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 

我想說:注入管理區域內的任何時候,用這個...

回答

2

寫自己時的狀態。

.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總是包含該字符串。如果我需要另一個自定義請求,我可以很容易地創建它,就像我對這個一樣。