I’m working on a solution that has a Core project with a DbContext (named CoreContext) in it. This context contains an entity (Product), among several others, that makes reference to an abstract class (ProductConstraints), that provides common validation rules for a general product. This context is never directly used. There are three other projects (Product1, Product2 and Product3) in the same solution that inherits both CoreContext (as ProductXContext) and ProductConstraints (as ProductXConstraints) class that implements custom validation rules for it’s specific product.
There’s also another project that contains a custom CodeFirstMembership. It’s ‘User’ entity contains a ‘Product’ property that defines the product the user will work with.
Finally, I have a MVC3 project where I want to instantiate the proper context based on the current user’s ‘Product’ information. Creating something like a ContextFactory that receives this product and returns the correct DbContext. I tried some approaches but with no significant success.
You can use dependency Injection to solve your problem. If the user is bound to only one product you can store that detail in
Sessionto avoid round trips to database.Then you can register the factory with your DI container.
Then you can use constructor injection in your controllers