在控制台应用程序的StructureMap中设置DbContext的最佳实践是什么? [英] what is the best practice to set up DbContext in StructureMap for console app?

查看:165
本文介绍了在控制台应用程序的StructureMap中设置DbContext的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是StructureMap,EF 4.1/POCO. 控制台应用程序假设要对一组数据运行2个后续操作,比如说operation1和operation2.我将DbContext设置为单例.这会在operation2中引起问题,因为operation1在其DbContext中留下了一些垃圾,这妨碍了operation2正常运行.同时,我无法将DbContext设置为每次调用",因为coz operation1使用2个存储库,它们通过它们的构造函数共享相同的DbContext.因此,理想情况下,在operation2之前,我需要重新初始化/重置/清理DbContext.有什么想法吗?

I use StructureMap, EF 4.1/POCO. Console app supposes to run 2 consequent operations upon some set of data, lets say operation1 and operation2. I set DbContext up as an singleton. This causes problem in operation2 as operation1 left some trash in its DbContext that prevent operation2 works well. In the same time I can not set up DbContext as 'per call' coz operation1 uses 2 repositories sharing the same DbContext passing through their constructor. So ideally I need reinitialize/reset/cleanup DbContext before operation2. Any ideas?

谢谢

推荐答案

仅使用两个不同的上下文.没有更好的解决方案来重置上下文,然后再创建一个新的上下文.如果您正在使用当前的架构,则只需对其进行改进以支持新的方案.无需传递上下文实例,而是传递一个上下文工厂,该工厂将能够根据需要创建任意数量的上下文实例.与存储库相同-您可以让工厂按需创建新的存储库实例.

Simply use two different contexts. There is no better solution to reset context then creating a new one. If you are fighting with your current architecture simply improve it to support new scenario. Instead of passing context instance pass a context factory which will be able to create you as many context instances as you need. Same with repositories - you can have factory to create a new repository instances on demand.

使用示例进行

让我们假设您正在使用 EFv4.1更新1 .它提供了新的接口IDbContexFactory<TContext>.您可以通过以下方式定义您的课程:

Let's suppose that you are using EFv4.1 Update 1. It offers new interface IDbContexFactory<TContext>. You can define your class this way:

public class YourClass
{
    private readonly IDbContextFactory<IYourContext> _factory;

    public YourClass(IDbContextFactory<IYourContext> factory) 
    {
        _factory = factory;
    }

    public void Operation1() 
    {
        using (IYourContext context = _factory.Create()) 
        {
            RepositoryA repository = new RepositoryA(context);
            RepositoryB repository = new RepositoryB(context);
            ...
        }
    }

    public void Operation2()
    {
        using (IYourContext context = _factory.Create()) 
        {
            RepositoryA repository = new RepositoryA(context);
            RepositoryB repository = new RepositoryB(context);
            ...
        }
    }
}

在这个示例中,您为上下文传递了工厂,但如果需要,可以对存储库执行相同的操作.

This was example where you pass factory for context but you can do the same for repository if you want to.

这篇关于在控制台应用程序的StructureMap中设置DbContext的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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