views:

51

answers:

2

I'm currently just starting to implement Dependency injection so i can start testing my code and have come across an issue many of times that i cant figure out.

My current case scenario:

I have a single class ( foo.cs ) that is active the whole time a windows service is running. Its responsible for polling the db for new messages then sending them out and update the db to reflect the success of the send.

My issue is that foo.cs has a dependency for the data access (Message Repository - a linq-to-sql data context) so its injected via the constructor and its life time scope is the same as foo. Everywhere I'm reading it says that a data context lifetime should be a single unit of work. So its like i need to inject the actual type i want to use and constructed it every time i want to do a single unit of work in foo rather than passing in a already constructed Repository that stays alive for the entire duration of the service.

+1  A: 

This reference discusses various alternatives. If your processing is effetively a sequence of all-or-nothing UOWs then a global context may actually be OK. If you have greater complexity then then approaches such as the per-thread or factory in the referenced articles may be more appropriate. In the latter case you would inject the factory rather than the context.

djna
+2  A: 

One possibility: Don't give the Foo class a data context directly during construction, but rather give it a data context 'factory' class/interface that implements a method that creates a fresh data context on each invocation.

**EDIT**

In case my description is unclear, here's a sketch of what I mean:

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())
        {
            //...
        }
    }
}
Daniel Pratt
thanks! works great
Waterboy4800