what is the best practice to set up DbContext in S

2020-07-30 00:46发布

问题:

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.