Dependecy Design Injecting and reusing a single data context

Currently, I am just starting to implement dependency injection, so I can start testing my code and have encountered a problem many times that I cannot understand.

My current scenario:

I have one class (foo.cs) that is active all the time when the Windows service is running. He is responsible for polling db for new messages, then sending them and updating db to reflect the success of sending.

My problem is that foo.cs has a dependency for accessing data (Message Repository - linq-to-sql data context), so its injection through the constructor and its lifetime are the same as foo. Wherever I read, it is said that the life of the data should be a single whole. So I like to enter the actual type that I want to use, and created it every time I want to do a separate unit of work in foo, and not pass it to the already built repository, which remains alive throughout the service.

+3
source share
2 answers

: Foo , "factory" , , .

** EDIT **

, , , :

interface IDataContextFactory
{
    ??? CreateContext();
}

class DataContextFactory : IDataContextFactory
{
    public ??? CreateContext()
    {
        // Create and return the LINQ data context here...
    }
}

class Foo
{
    IDataContextFactory _dataContextFactory;

    public Foo(IDataContextFactory dataContextFactory)
    {
        _dataContextFactory = dataContextFactory;
    }

    void Poll()
    {
        using (var context = _dataContextFactory.CreateContext())
        {
            //...
        }
    }
}
+4

. UOW, . , , factory , . factory, .

+2

Source: https://habr.com/ru/post/1760115/


All Articles