IDisposable on an injected repository

后端 未结 2 745
执笔经年
执笔经年 2021-02-04 16:33

I have the following ADO .Net Repository

public class Repository : IRepository, IDisposable
{
   private readonly IUnitOfWork UnitOfWork;
   private SqlConnectio         


        
2条回答
  •  我寻月下人不归
    2021-02-04 17:12

    The problem you have is one of ownership. The UserDomainService class does not create the IRepository, yet it still takes the ownership of that instance, since it disposes it.

    The general rule is that the one who creates an object should distroy it. In other words, he who creates the object is the owner, and the owner shall destroy that object.

    There are two solutions to your problem.

    1. Create a IRepositoryFactory, as Adam clearly explains. A CreateNewRepository() method on such a factory will clearly communicate that the caller gets the ownership and should dispose that created repository.

    2. Let the one who creates (and injects) that repository deal with the disposal of that repository. Either you do this manually in your WCF service, or you use an IoC/DI framework. In case you use a DI framework, you should probably look at a Per Web Request lifetime, or something similar.

    Last note, your IRepository implements IDisposable. When choosing solution 2, you can remove the IDisposable interface from IRepository, which hides the fact that resources are involved from the application. Hiding IDisposable from the application is a good thing, since that interface is a leaky abstraction. You already encountered this, since calling Dispose from within the application, breaks the entire application.

提交回复
热议问题