0

In support of multi-tenancy, setting up routing:

{controller}/{tenantId}/{action}/{id?}

When the controller is instantiated, via the IoC framework in MVC6, the constructor takes a model (IUserStore<ApplicationUser>) that manages access to users and needs the tenantId in its constructor. The DI container is barfing right now b/c it doesn't have the tenantId.

I'd like to be able to register the model thusly:

services.TryAddTransient(typeof(IUserStore<CazadorUser>, (IServiceProvider isp) =>
{
     return new TenantUserStore<ApplicationUser>(isp.GetService<DbContext>(), "Can I get the tenant ID from the IServiceProvider as its in the route?");
 }));

If I cannot access the parsed route, is there another way to get the tenant ID into the DI-hydrated controller (or, rather, the ctor parameter of the DI-hydrated controller that is DI-hydrated)?

pomeroy
  • 1,377
  • 1
  • 12
  • 21
  • I am curious, What are you trying to achieve ? You will get the tenantId in your action method. Is that not enough to pass to your other layers ? – Shyju Dec 26 '15 at 00:32
  • @Shyju I would like the IUserManager impl that supports multitenancy to be passed to the controller via DI. It seems like the happy path for MVC 6, and I kind of buy into DI. – pomeroy Dec 26 '15 at 00:40
  • 1
    DI containers are meant for [composing object graphs](http://blog.ploeh.dk/2011/07/28/CompositionRoot/) (typically once at application startup), not for defining runtime behavior. When you need to change a dependency at runtime, you should turn to [abstract factory](http://blog.ploeh.dk/2014/12/24/placement-of-abstract-factories/) or the [strategy pattern](http://stackoverflow.com/questions/1499442/best-way-to-use-structuremap-to-implement-strategy-pattern#1501517). – NightOwl888 Dec 26 '15 at 03:46
  • Do not inject runtime data into your constructors; that's [an anti-pattern](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99). – Steven Dec 27 '15 at 13:53

0 Answers0