简体   繁体   中英

asp.net mvc3 Code First (Database Singleton)

I am working on asp.net mvc using code first. I noticed that once i create a new controller, the controller template shows dispose overridden method that just has one job; dispose db variable created at the top of this controller.

I am thinking of changing this to use singleton pattern with my DBContext class.

I tried it and it worked fine. except that i needed sometimes to access database from 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).

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. 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).

We also access the context in global asax to do db initialization and seeding for development. Again, you can use a DI container to get an instance of the EF context.

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. 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 does not let you attach entities to multiple contexts, and we use singleton per http context for this reason.

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