Share a data context across various model repositories in ASP.NET MVC using LINQ2SQL

asp.net-mvc, c#, linq-to-sql

Solution

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.

Problem

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.

Original source