4

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.

2
  • Which approaches did you try? What failed? Commented Jan 2, 2012 at 19:51
  • I tried using reflection but I ended with some dependency problems. Commented Jan 4, 2012 at 13:00

1 Answer 1

3

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)
     {

     }    
}
Sign up to request clarification or add additional context in comments.

2 Comments

Users can work with many products, but one at a time so the session variable approach will work. I'm aware of the DI concept but never used a DI Container before. I'll give MSUnity a try.
Finally went back to the project and managed to successfully use a container to create a factory. Everything is working now. But my MVC project still have references to my three product contexts... I'm going to try removing these references and actually inject them using Unity. I'm marking your reply as an answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.