简体   繁体   English

asp.net mvc3代码优先(数据库单例)

[英]asp.net mvc3 Code First (Database Singleton)

I am working on asp.net mvc using code first. 我首先使用代码在asp.net mvc上工作。 I noticed that once i create a new controller, the controller template shows dispose overridden method that just has one job; 我注意到,一旦创建了一个新的控制器,该控制器模板就会显示仅处理一项工作的dispose覆盖方法。 dispose db variable created at the top of this controller. 处置在此控制器顶部创建的db变量。

I am thinking of changing this to use singleton pattern with my DBContext class. 我正在考虑将其更改为在我的DBContext类中使用单例模式。

I tried it and it worked fine. 我尝试了一下,效果很好。 except that i needed sometimes to access database from global.asax. 除了我有时需要从global.asax访问数据库。 (sometimes) is throws an exception. (有时)会引发异常。

Have anyone thought to do the same? 有没有人想过这样做? Any ideas? 有任何想法吗?

Thank you 谢谢

personally I would follow a completely different approach, see my answer here: https://stackoverflow.com/a/7474357/559144 I would not use Singleton and would not hardlink MVC which is a UI framework with the DAL (EF in your case). 我个人将采用完全不同的方法,请在此处查看我的答案: https ://stackoverflow.com/a/7474357/559144我不会使用Singleton,也不会将MVC硬链接到DAL(在您的情况下为EF) )。

about not using singleton, let the database handle concurrency; 关于不使用单例,让数据库处理并发; it's one of the things Database servers do the best ;-) 这是数据库服务器最好的事情之一;-)

We use EF context as a singleton per http context. 我们使用EF上下文作为每个http上下文的单例。 I also would not hard link EF with MVC, but you can still be sure that each http context deals with a single EF context instance by using dependency injection (we use Unity). 我也不会将EF与MVC进行硬链接,但是您仍然可以通过使用依赖项注入(我们使用Unity)来确保每个http上下文都处理单个EF上下文实例。

We also access the context in global asax to do db initialization and seeding for development. 我们还访问全局asax中的上下文,以进行数据库初始化和种子开发。 Again, you can use a DI container to get an instance of the EF context. 同样,您可以使用DI容器获取EF上下文的实例。

public interface IUnitOfWork : IDisposable
{
    int SaveChanges();
}

public class MyEfContext : DbContext, IUnitOfWork
{
    // your custom context code
}

Using a singleton-per-http-context lifetime for the IUnitOfWork dependency injection isn't an approach to help deal with concurrency in our case. 在IUnitOfWork依赖项注入中使用每个HTTP上下文的生存期并不是在我们的案例中帮助处理并发的方法。 We do it because when dealing with EF entities, we need to make sure all of the selects / inserts / updates / deletes always happen with the same context instance. 我们这样做是因为在处理EF实体时,我们需要确保所有选择/插入/更新/删除操作始终在同一上下文实例中进行。 EF does not let you attach entities to multiple contexts, and we use singleton per http context for this reason. EF不允许您将实体附加到多个上下文,因此,每个http上下文使用单例。

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

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