How to use one database context for all instances that make use of a repository?

孤街醉人 提交于 2019-12-08 10:44:30

问题


I have made some architectural MVC-mistake since I did not know of the

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

error.

My setup is as follows: I have a repository for accessing the database which creates an instance of dbcontext, I have controllers that instantiate managers they need, the managers all instantiate their own repository. Here is the problem, when a controllers uses more than one manager to collect data and then try to create an object that uses this data, the error above appears when adding the object to the dbcontext.

I read about the UnitOfWork pattern, but it seems like a lot of work to restructure my code around that. Is there a quick fix to be able to update the database and avoid the error?

Thanks.


回答1:


I think that one of the ways to fix your problem in quick way will be to add dependency injection. Of course in ideal world repositories should have only DbContext instance and do not know nothing about how it was created.

You have not provided any code samples so I will present very simple examples.

In this example Autofac is used as IoC container. Write this code in Global.asax.Application_Start method.

var builder = new ContainerBuilder();
builder.RegisterType<YourDbContext>().As<IYourDbContext>().InstancePerRequest();

And then in your repository:

public class Repository1
{
    public IYourDbContext DbContext { get; private set; }

    public Repository1()
    {
        // How it's probably have been before
        // DbContext = new YourDbContext();

        // Getting DbContext from IoC container
        DbContext = (IYourDbContext) DependencyResolver.Current.GetService(typeof (IYourDbContext));
    }
}

If you don't want to add extra libraries, you could save DbContext instance at HttpContext.Current.Items.



来源:https://stackoverflow.com/questions/29221881/how-to-use-one-database-context-for-all-instances-that-make-use-of-a-repository

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