How do you centralize the Entity Framework data context in a web application?

五迷三道 提交于 2019-12-04 17:31:17

Use constructor injection on the repository to pass the context.

public class UserRepository : IUserRepository
{
    Entities dataContext;

    public UserRepository(Entities entities)
    {
       this.dataContext = entities;
    }

    public User GetUser(string username)
    {
        return dataContext.Users.SingleOrDefault(x => x.Username == username);
    }

    // ... more CRUD-style methods that are not relevant to this question.

    public void SaveChanges()
    {
        dataContext.SaveChanges();
    }
}

Tell your DI container to request-scope the context lifetime.

E.g., with AutoFac you would:

builder.RegisterType<Entities>().InstancePerHttpRequest();
builder.RegisterType<UserRepository>().As<IUserRepository>().InstancePerHttpRequest();
builder.RegisterControllers(typeof(MvcApplication).Assembly);

We've had the exact same issue. You should use the Unit of Work design pattern. Read more here: http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Personally I prefer the method where you pass the username and role and it has all the db logic in the repository for adding a user to the database. If you called this method 10 times, you would not want to get the role and add it to the user object in 10 different places within your MVC application.

Let the repository do all the work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!