C# 由引用其创建者的IDisposable创建的对象是否应处置该创建者?

C# 由引用其创建者的IDisposable创建的对象是否应处置该创建者?,c#,idisposable,object-lifetime,C#,Idisposable,Object Lifetime,我有一个类根据实现IDisposable,因为它包含对HttpClient的引用。它看起来像这样: public class CustomServiceClient : IDisposable { HttpClient client; // ... public ServiceCreatedEntity GetEntity() { // ... } ~CustomServiceClient() { this.Dispose(false); }

我有一个类根据实现IDisposable,因为它包含对HttpClient的引用。它看起来像这样:

public class CustomServiceClient : IDisposable
{
  HttpClient client;

  // ...

  public ServiceCreatedEntity GetEntity()
  {
    // ...
  }

  ~CustomServiceClient()
  {
    this.Dispose(false);
  }

  private bool disposed = false;
  void IDisposable.Dispose()
  {
    if(!disposed)
    {
      this.Dispose(true);
      GC.SuppressFinalize(this);
      disposed = true;
    }
  }

  public void Dispose(bool disposing)
  {
    if(disposing)
    {
      // dispose managed resources
      client.Dispose();
    }

    // dispose unmanaged resources - this class has none
  }
}

public class ServiceCreatedEntity
{
  CustomServiceClient client;

  public ServiceCreatedEntity(CustomServiceClient client)
  {
    this.client = client;
  }

  // some functions that use client
}

我想知道
serviceCreateIdentity
是否应该实现IDisposable并处理CustomServiceClient。我预计
CustomServiceClient
通常比
ServiceCreatedEntity
有更长的生存期,我担心客户会处置
ServiceCreatedEntity
,并对其
CustomServiceClient
的处置原因感到困惑。任何提示都将不胜感激

问题更多的是什么创造了什么。。。创建者应(通常)在面向请求的环境中处理拆卸。

ServiceCreateIdentity不应处置客户端,但如果它依赖于客户端,则在客户端上包含IsDisposed属性或Disposing事件不会造成伤害,以便ServiceCreateIdentity可以在使用客户端之前验证客户端是否未被处置,或者让CustomServiceClient在处理后使用时抛出一个错误。

我不明白为什么
CustomServiceClient
有一个返回
ServiceCreateIdentity
的方法,而
ServiceCreateIdentity
CustomServiceClient
作为其构造函数中的参数

通常,如果传入对象,则不应在该对象中处理该对象。如果一个对象创建了一个
IDisposable
,它应该自己实现
IDisposable
,并处理它。对于任何其他情况(如IOC容器,或一些花哨的东西),考虑对象的寿命和何时将被处理。
查看更多关于
IDisposable

的信息,不确定这是否有帮助,但这让我想起了。TL,DR:“当您调用dispose时,StreamReader、StreamWriter、BinaryReader和BinaryWriter都会关闭/处理它们的底层流。”,TL,DR:如果您将GC留给它,它“将调用dispose(false),这将不会处理底层流。”。只是想让你对类似的情况有所了解。NET@tnw-我考虑过了。我想我可以向我的用户提供文档,建议他们只处理
ServiceCreatedEntity
,如果他们也处理了客户端。但这里的区别在于,StreamReaders/Writer/等是使用新操作符(RAII和所有这些)显式创建的,因此创建者应该“拥有”对象,而
ServiceCreateIdentity
是由
CustomServiceClient
实例化并返回的,这表明,也许造物主并不拥有它。