Is it possible to have multiple dependency resolvers in ASP.NET MVC 3? -
is possible have more 1 dependency resolver in asp.net mvc 3 (similar case of modelbinders , providers)?
there 1 scenario think of having multiple 'containers' or 'resolvers' useful , multi-tenancy. multi tenancy run multiple customers (organizations, own set of users) in same web application, , dynamically switch based on login, request info, or domain info.
still, dependencyresolver.current
-as darin noted- static, there's nothing can (or should this). however, hide multiple containers behind single idependencyresolver
abstraction , return implementation based on criteria. might this:
public class multitenantdependencyresolver : idependencyresolver { func<int> tenantidselector,; idictionary<int, idependencyresolver> tenantresolvers; public multitenantdependencyresolver( func<int> tenantidselector, idictionary<int, idependencyresolver> tenantresolvers) { this.tenantidselector = tenantidselector; this.tenantresolvers= tenantresolvers; } private idependencyresolver currentresolver { { return this.tenantresolvers[tenantidselector()]; } } public object getservice(type servicetype) { return this.currentresolver.getservice(servicetype); } public ienumerable<object> getservices(type servicetype) { return this.currentresolver.getallinstances(servicetype); } }
the following code snippet shows usage of multitenantdependencyresolver
:
var tenantresolvers = new dictionary<int, idependencyresolver> { { tenants.abcid, buildresolver(registerfortenantabc) }, { tenants.klmid, buildresolver(registerfortenantklm) }, { tenants.xyzid, buildresolver(registerfortenantxyz) }, }; var multitenantresolver = new multitenantresolver( () => gettenantidfromurl(), tenantresolvers); dependencyresolver.setresolver(multitenantresolver); private static int gettenantidfromurl() { // todo: return tenant id } private static idependencyresolver buildresolver( action<ikernel> tenantspecificregistrations) { var kernel = new kernel(); // todo: tenant agnostic registrations. instance kernel.bind<itimeprovider>().to<systemtimeprovider>(); tenantspecificregistrations(kernel); return new ninjectdependencyresolver(kernel); } private static void registerfortenantabc(ikernel kernel) { // todo: regisrations abc tenant. instance kernel.bind<ilogger>().to<abctenantlogger>(); }
Comments
Post a Comment