views:

29

answers:

1

I have a 2 repositories in my application each with their own datacontext objects.

The end result has me attempting to attach an object retrieved from one repository to an object retrieved from a different repository which results in an exception.

+2  A: 

Use Constructor Injection to inject the DataContext into each Repository:

public class MyRepository : IMyRepository
{
    private readonly DataContext dataContext;

    public MyRepository(DataContext dataContext)
    {
        if(dataContext == null)
        {
            throw new ArgumentNullException("dataContext");
        }

        this.dataContext = dataContext;
    }

    // implement MyRepository using this.dataContext;
}

This allows you to share or not share the DataContext in whichever way is necessary.

Mark Seemann