如何使用一个数据库上下文为利用一个仓库的所有实例? [英] How to use one database context for all instances that make use of a repository?

查看:201
本文介绍了如何使用一个数据库上下文为利用一个仓库的所有实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经取得了一些建筑MVC-的错误,因为我不知道的。

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

这是实体对象不能由IEntityChangeTracker的多个实例被引用。

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

错误。

我的设置是如下:我有一个访问它创建的DbContext 的一个实例数据库,我有一个实例管理​​他们所需要的管理​​的所有实例化自己的。这里的问题是,当一个控制器使用多个管理​​来收集数据,然后尝试创建一个使用此数据的对象,错误添加对象时,上面出现在的DbContext

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.

我读到有关的UnitOfWork模式,但它似乎是一个大量的工作来调整左右,我的code。是否有一个快速修复能够更新数据库,并避免错误?

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?

感谢。

推荐答案

我认为的一种方式来修复快捷方式您的问题将是添加依赖注入。当然,在理想世界里库应该只有的DbContext 实例,不知道任何关于它是如何创建的。

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.

您没有提供任何code样品,所以我会present非常简单的例子。

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

在这个例子中 Autofac 作为IoC容器。写 Global.asax.Application_Start这个code 方法。

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));
    }
}

如果您不想增加额外的库,可以为您节省的DbContext 实例在 HttpContext.Current.Items

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

这篇关于如何使用一个数据库上下文为利用一个仓库的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆