سؤال

Is there a way to make a binding that would say "when injecting IService into any controller within an area Admin inject this instance"?

We have numerous controllers in Admin which might use the same service. We could write bindings for each and every controller but then another controller might be introduced with the same service and the developer forgets to wire it up specifically for the Admin (which uses different set of service implementations than other Areas or outside of an Area).

// 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

I'd like to say: when injecting into anything within the Admin area, use this...

هل كانت مفيدة؟

المحلول

Write your own when condition.

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

Update by @mare:

I'm going to update your answer with details on how I solved it. You did point me in the right direction and it was easy enough to get from your answer to the correct solution. This is what I've done:

// 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();

Since all my controllers are in xyz.Areas.Admin namespace, the FullName always contains that string. Should I need another custom request I can easily create it as I did with this one.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top