简体   繁体   English

初始化并将数据库名称作为参数传递给具有整个类范围的DbContext对象

[英]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. 我正在使用EF 6开发多租户MVC 5应用程序。对于每个用户,我都覆盖了Entities构造函数以获取数据库名称作为参数。 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. 用户登录时,其数据库名称将加载到会话中,然后它将传递给Entities构造函数。 All is good but here is the problem, 一切都很好,但这是问题所在,

I want to declare the Entities object having scope of class in my controllers. 我想在控制器中声明具有类范围的Entities对象。 Now: 现在:

  1. A session is only accessible inside a method(ActionResult), so cannot be used in a class scope. 会话只能在方法(ActionResult)内部访问,因此不能在类范围内使用。
  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. 如果我在所有使用Entites的ActionResults中初始化实体对象,则该应用程序可以正常工作,但我不想一次又一次地初始化对象。
  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. Web.config文件中没有维护任何连接字符串,对于作为参数传递的数据库名称,在代码内部生成了ConnectionString,因此我无法使用ConfigurationManager类。

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. 如果我在所有使用Entites的ActionResults中初始化实体对象,则该应用程序可以正常工作,但我不想一次又一次地初始化对象。

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. 因此,只要用户发出请求,就可以使用该密钥创建数据库连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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