I am running into an interesting scenario that I just haven't been able to get answers on. I would like to see if there are elegant solutions for this. Here are some use cases:
I want to pass the identity/user principal of the user that called an API Action in a Controller to Services and Repository layers. There are important decisions that get taken at Service layer depending on the User's claims and/or privileges/permissions.
I want to identify a tenant (occurs using HTTP Headers or Hostnames) but pass this Tenant information to Services and Repository layers so that different Redis Caches and Databases can be used depending on the Tenant.
I can easily build a method in a base service called WithTenant(object tenant); which I can use to pass tenants.
This means every service call I make will need this WithTenant called.
For e.g. a call:
will now change to:
Likewise, if I want to pass the HttpRequest in addition to the Tenant, I will have to do this:
This gets even more complex as I need to pass this to the Repository layer. My Mongo DB Context is a singleton. I might need to change this to accept the tenant so the connection string can be changed based on the tenant.
So I was thinking:
- Isn't there a way by which I can pass a Context object across these layers? Maybe build a Context class and set properties like Request, or Tenant or anything else I need and then pass it across layers?
- More importantly, is there a way to dynamically inject this into the Constructors of these services so I don't need to manually wire it up again? I know that I can store my context in the Request object or maybe even an Owin Context. Could I somehow inject that? If so I haven't seen any good examples of this across multiple layers.
I guess I'm simply trying to simplify the ability to pass state between layers. Cross cutting functions like Caching, Logging, Database Access change on a per Tenant basis so if I could create a central context, that would greatly simplify things.
Any thoughts? Would love to see what others are doing to solve such problems.