what is the best practice to set up DbContext in StructureMap for console app?

送分小仙女□ 提交于 2019-12-22 01:40:21

问题


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?

Thanks


回答1:


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.

Edit with example:

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.



来源:https://stackoverflow.com/questions/7112201/what-is-the-best-practice-to-set-up-dbcontext-in-structuremap-for-console-app

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