问题
I’m developing a MVC Website based in codeplex EFMVC solution, and I’m using Entity Framework and Repository, Unit of Work and Command Patterns. My website needs to be a SaaS solution (software as a service) multiple database. In my legacy Asp.Net WebForms I have a XML file that holds all the different string connections and I’m trying to use the same strategy. So in my LoginController I create a command that has company (to identify in which database will be connected) username and password. At Validate() method in Domain project, I’m reading the XML to get the correct string connection based on company field. My problem is how can I set the DatabaseFactory or DbContext to use this selected connection string? It should be injected at the constructor? Any suggestion for doing this in the correct way, without “breaks the rules”?
Note that I’m using AutoFac for Dependency Injection.
Thanks for your attention.
Best Wishes,
Luiz Fernando Vall Dionizio
回答1:
You can use the ResolveNamed feature of Autofaq to get different registration for the same Interface For instance:
builder.Register<IDataContext>(x => new DataContext(connectionStringOne))
.Named<IDataContext>("CS1");
builder.Register<IDataContext>(x => new DataContext(connectionStringTwo))
.Named<IDataContext>("CS2");
and to resolve it
var context = ContainerAccessor.Container().ResolveNamed<IDataContext>("CS1");
Another way is to override the DataContext ctor and read the configuration from an shared location for that request.
来源:https://stackoverflow.com/questions/14570180/multiple-string-connections-in-ef-dbcontext