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

I am working on a solution having a Core project with a DbContext (named CoreContext ). This context contains an object (Product), among several others, that refers to an abstract class (ProductConstraints) that provides general validation rules for a common product. This context is never used directly. In the same solution, there are three other projects (Product1, Product2, and Product3) that inherit the CoreContext class (like ProductXContext) and ProductConstraints (like ProductXConstraints), which implements custom validation rules for a particular product.

There is also another project containing a custom CodeFirstMembership . The User object contains the Product property, which defines the product with which the user will work.

Finally, I have an MVC3 project where I want to create an appropriate context based on the information of the current user. Create something like ContextFactory that will receive this product and return the correct DbContext . I tried some approaches, but without significant success.

+4
source share
1 answer

You can use the Injection dependency to solve your problem. If the user is tied to only one product, you can save this part in Session to avoid rounding to the 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 using the 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) { } } 
+3
source

Source: https://habr.com/ru/post/1388973/


All Articles