DI with disposable objects

Suppose my repository class is as follows:

class myRepository : IDisposable{ private DataContext _context; public myRepository(DataContext context){ _context = context; } public void Dispose(){ // to do: implement dispose of DataContext } } 

I now use Unity to control the lifetime of my repository and the data context, and set the lifetimes as:
DataContext - singleton
myRepository - create a new instance every time

Does this mean that I should not implement IDisposable in the repository to clear the DataContext?

Any guidance on such issues?

EDIT: DataContext - singleton - read this as a single line website request

+2
source share
3 answers

As a rule, abstract dependencies should not be inferred from IDisposable , because it will be Leaky Abstraction . A dependency may or may not contain unmanaged resources that are implementation-specific. In any case, the container must control the lifetime , so for him this does not correspond to the consumer - he does not know the dependence on the lifetime: it could be used with other consumers, and in this case it would be destructive to prematurely dispose of .

However, a DataContext (LINQ to SQL?) Presents another problem, since it already implements IDisposable, and you cannot very well change this because it is defined in BCL.

You can correctly implement IDisposable for your repository, but that means that for all repositories and datacontext you need to match the lifetime .

Another alternative is to simply ignore that you are holding onto a one-time resource, but if you do, you will need to make absolutely sure that Unity will correctly manage the DataContext at the appropriate time - but since you plan on using the Singleton lifetime, this should not be a problem .

+4
source

If I were you, I would either execute UnitOfWork or let the IOC container manage the life cycle of your DataContext.

Structuremap, for example, has an HttpContextScoped parameter, so you register your DataContext as follows:

 For<DataContext>().HttpContextScoped().Use<MyDataContext>(); 
+3
source

Does this mean that I should not implement IDisposable in the repository to clear the DataContext?

It sounds like this: from what you say, all repositories will have the same DataContext , but the first repository you created will get rid of it.

What creates a DataContext ? Whatever it is, he must get rid of it.

0
source

Source: https://habr.com/ru/post/886672/


All Articles