Henrique Miranda
Henrique Miranda

Reputation: 1108

How to dynamically switch between multiple contexts (of same base) in Code First

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.

Upvotes: 4

Views: 879

Answers (1)

Eranga
Eranga

Reputation: 32437

You can use dependency Injection to solve your problem. If the user is bound to only one product you can store that detail in Session to avoid round trips to database.

public class ContextFactory
{    
     public CoreContext CreateContext()
     {
         var product = HttpContext.Current.Session["Product"] as string;

         //resolve the correct context

         return context;
     }
}

Then you can register the factory with your DI container.

builder.Register(c => ContextFactory.CreateContext()).As<CoreContext>();

Then you can use constructor injection in your controllers

public class MyController : Controller
{
     public MyController(CoreContext context)
     {

     }    
}

Upvotes: 3

Related Questions