Repository pattern where does data context dispose go?

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

Solution

If you are using a `using` statement, which you should be doing, the call is automatically disposed as it implements the `IDisposable` interface.

Such as:

public int GetThingCount()
{
    using (MyDataContext context = new MyDataContext())  // context is created here
    {
        return context.Things.Count();
    } // it is automatically disposed of here even in the event of an exception
}

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

Problem

Watching few examples that use repository pattern like StoreFront I couldn't figure out where is `context.Dispose()` called? Wouldn't not disposing of data context lead to memory leaks? or is it just one Data context for each respoitory for the lifetime of application?

Original source