DataContext Lifetime, LinqToSql

I found an article on the Internet that presented how to implement a repository template. The implementation looks something like this:

class ProductRepository : IProductRepository { var context; public ProductRepository() { this.context = new MyDataBaseDataContext(); } // the rest of methods } 

But I'm not quite sure if this is right, what happened to the context? Does the garbage collector dispose of this object? Or is it better to create a context using (...) {} an operator?

+4
source share
3 answers

Repository should not open the data context, the DataContext should be passed to it, since it should not own it. Suppose you have an operation that needs to be in a transaction and includes several repositories, what would you do?

You need to use the UnitOfWork template .

In this template, a UoW (which wraps the DataContext ) is passed to the repository.

In practice , the ProductManager in the business layer is created by Unit Of Work .

+2
source

The simple answer to this question is that the repository must necessarily delete the data context itself, and not allow it to be terminated by the .NET runtime. This can be achieved by running the standard .NET hosting template ...

 class ProductRepository : IProductRepository, IDisposable { var context; public ProductRepository() { this.context = new MyDataBaseDataContext(); } // the rest of methods public void Dispose() { if (context != null) { context.Dispose(); context = null; } } } 
+1
source

I assume that this depends on whether you need transactions in the repository operations and what is the need to track changes. Datacontext data can be extremely useful, as it can allow you to get a bunch of objects, modify them in the application, and then just call SubmitChanges / RollbackChanges at any time convenient for you. But if you do not expose this function in your repository, you are probably best off using the “use” of the instance in each repository method, as this will save memory usage and resources for tracking changes.

0
source

All Articles