简体   繁体   中英

Initialize and pass database name as parameter to DbContext object having scope of whole class

I am developing a multi-tenant MVC 5 app using EF 6. For each user I have override the Entities Constructor to get a database name as a parameter. I have stored the database name in another code first database maintained against all users. When a user logged in, his database name is loaded in a session and then it will pass to the Entities constructor. All is good but here is the problem,

I want to declare the Entities object having scope of class in my controllers. Now:

  1. A session is only accessible inside a method(ActionResult), so cannot be used in a class scope.
  2. Static variables cannot be used.
  3. The app can work if I initialize the entities object inside all ActionResults which uses Entites, but I don't want to initialize an object again and again.
  4. There is no connection string maintained in the Web.config file, ConnectionString is generated inside the code against the database name passed as a parameter, So I cannot use ConfigurationManager class.

What I want to do is:

public class ABCController : BaseController //BaseController has all Sessions
{
    private MyEntities db = new MyEntities("dbName"); //dbName is a session
    // all code and ActionResults here
}

How can I do it?

The app can work if I initialize the entities object inside all ActionResults which uses Entites, but I don't want to initialize an object again and again.

Why not? That's exactly what you should be doing.

Even if it were a class-level member, controller instances don't persist across requests. So you'd be instantiating it for every request a user makes anyway. All this approach does is move that instantiation to before the user context is made available.

Any time a user makes a request to the application, you have that user's context. (In this case from session.) That context includes the key for your database connection. So any time a user makes a request, use that key to create the database connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM