0

I'm using constructor injection in my controllers to work with multiple contexts (EF code first) via a contextFactory registered in my DI container. I have 3 ProductXContexts that inherit from my CoreContext. I have each context in a separate project. Currently they are all referenced in my MCV project. I want to keep the base context (CoreContext) referenced but remove the ProductXContext references and use Unity to resolve and inject the dependences at runtime.

Currently I'm using fluent configuration to set up my container:

var container = new UnityContainer();
container.RegisterType<CoreContext>(new InjectionFactory(c => ContextFactory.CreateContext()));

The context factory looks like this:

public static CoreContext CreateContext()
{
    var userProduct = HttpContext.Current.Session["Product"] as string;
    CoreContext context;

    switch (userProduct)
    {
        case null:
            throw new Exception("No product is selected. Can't define an appropriate context.");
        case "Product 1":
            context = new Product1Context();
            break;
        case "Product 2":
            context = new Product2Context();
            break;
        case "Product 3":
            context = new Product3Context();
            break;
        default:
            throw new Exception("Current product is not supported. Can't define an appropriate context.");
    } 
    return context;
}

And controllers are like this:

public class MyController : Controller
{
    private CoreContext _context;

    public MyController(CoreContext context)
    {
        _context = context;
    }
...
}

So it seems I have to switch over to XML configuration if I'm going to remove ProductXContext references from my MVC project since in order to compile fluent code you must have references to all the code. But I have now idea of:

  1. how to declare the InjectionFactory in XML configuration.
  2. if I manage to declare it, how to instantiate ProductXContext inside my ContextFactory since I don't have reference to them anymore.

PS: Is there a way to register the external types using XML config and then declare the injectionFactory using fluent config?

Thanks in advance!

Henrique Miranda
  • 1,030
  • 1
  • 13
  • 31

1 Answers1

0

If you need support for late-binding without direct references to your ProductXContext projects there are alternative solutions. The TecX project contains an enhanced configuration engine for Unity that allows you to scan assemblies for implementations of certain types and registers them automatically. It also has a feature from Castle Windsor called Typed Factories that auto-generates factories like your ContextFactory.

Sebastian Weber
  • 6,766
  • 2
  • 30
  • 49