Steve P.
Steve P.

Reputation: 11

MEF, entity framework and constructor injection

First time asking a question, long time reader.

We have a new application that makes heavy use of MEF and DI (through constructor parameter injection) to handle object instantiations. One area we're struggling with is the EF context creation. To create the EF context, you need a conn string (in app.config, for example). But our app let's users supply the server/db (along with username / password) at launch. So the question is how can we use MEF to instantiate the EF context with a default conn string and then replace the conn string after login with the user-supplied values and then update that in the MEF container?

The only way we've handled it so far is in the LoginViewModel to use an IoC.Get type call to pull the existing entities object out of the container, then set its connection string with new values. MEF then uses this new string moving forward and creates/disposes the context automagically as we inject it around the app.

The concern is this smells of service locator (and occurs outside the composition root) among other problems like MEF + DI + container usage. Many commenters note that blind adherence to a pattern is a recipe for disaster. The question is if this is the appropriate way to handle this scenario? Should we use an abstract factory that is created, then use it to create the context later?

How to replace a connection string for EF when the context is created in the bootstrap part of the app and thus already instantiated when a new conn string is supplied at login? MEF normally repeatedly creates/disposes the context - so how to set a new conn string? We create the context part with the shared policy so that in theory there's only one and never destroyed so just updating the conn string should work.

Upvotes: 1

Views: 829

Answers (1)

Hesham
Hesham

Reputation: 371

We faced similar situation for our multi-tenant MVC Azure based application, and we solved by Exporting a method to get the current connection string from the active session of the user requesting database operation

Exporting the method abstract the DbContext from the MVC session details, just import the exported method in your DbContext or IRepository implementation.

Don't use property exports, when property exported, its value is saved by MEF and will not get the current value stored in the active session. Method export will enable you to get the current value of connection string stored in the active session.

Let me know if you need more clarification.

Upvotes: 1

Related Questions