依赖注入和IDisposable [英] Dependency Injection and IDisposable

查看:97
本文介绍了依赖注入和IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于带有Autofac用法的 IDisposable 实现中的 Dispose()方法,我有些困惑>

说我对物体有一定深度:




  • 控制器取决于 IManager ;

  • Manager 取决于 IRepository ;

  • 存储库取决于 ISession ;

  • ISession IDisposable



这将导致以下对象图:

  new Controller(
新Manager(
新存储库(
new Session())));

我是否还需要使Manager和Repository也实现IDisposable并调用Manager.Dispose()?控制器,Manager中的Repository.Dispose()等,或者Autofac是否会自动知道调用堆栈中的哪些对象需要正确处理?控制器对象已经是IDisposposable的,因为它是从基本ASP.NET Web API控制器派生的。

解决方案

资源的一般规则是:


拥有资源的人负责处置该资源。


这意味着,如果类拥有资源,则它应该以与创建它时相同的方法对其进行处置(在这种情况下,可处置对象称为临时性),或者,如果这不可能,则通常意味着类必须实现 IDisposable ,以便它可以通过 Dispose 方法处理资源。



但要注意的是,一般来说,一个类只要负责其创建,就应该拥有。但是,当注入资源时,这意味着该资源在使用者使用之前就已经存在。使用者没有创建资源,在这种情况下,应该处置它。尽管您可以将资源的所有权传递给使用者(并在传递所有权的类文档中进行交流),但是通常您不应该传递所有权,因为这会使您的代码复杂化,并使应用程序非常脆弱。



尽管在某些情况下转移对象所有权的策略可能是有意义的,例如对于属于可重用API的类型的类型(例如 System .IO.StreamReader ),在处理属于对象图一部分的组件时总是很糟糕的(我们所谓的注射剂)。我会在下面解释原因。



因此,即使您的 Controller 依赖于需要处理的依赖项,您的控制器不应处理它们:




  • 由于消费者未创建此类依赖关系,因此不知道其依赖关系的预期寿命是多少是。依赖性应该比消费者更长寿。在这种情况下,让使用者处理该依赖关系将导致应用程序中的错误,因为下一个控制器将已经处理依赖关系,这将导致 ObjectDisposedException

  • 即使依赖项的生活方式与消费者的生活方式相同,处置仍然不是一个好主意,因为这使您无法轻松地将该组件替换为可能更长的组件。一生的未来。一旦将该组件替换为寿命更长的组件,就必须遍历所有它的使用者,这可能会导致整个应用程序发生重大变化。换句话说,这样做会违反打开/关闭原则

  • 如果您的消费者能够消除其依赖性,则意味着您实现了 IDisposable code>上的抽象。这意味着此抽象是泄漏实现细节 –违反了依赖反转原理。在抽象上实现 IDisposable 时,您会泄漏实现细节,因为该抽象的每个实现不太可能需要确定性处理,因此您定义了考虑到特定实现的抽象。消费者无需了解有关实现的任何信息,无论它是否需要确定性处置。

  • 让该抽象实现 IDisposable 导致您违反接口隔离原则,因为该抽象现在包含一个额外的方法(即< (code> Dispose ),并非所有消费者都需要致电。他们可能不需要调用它,因为-正如我已经提到的-资源可能会超过消费者的寿命。在那种情况下,让它实现 IDisposable 很危险,因为任何人都可以对其调用 Dispose 导致应用程序中断。如果您对测试更加严格,这也意味着您必须测试使用者是否使用不调用 Dispose 方法。这将导致额外的测试代码。这是需要编写和维护的代码。



因此,您应该 only 实施实现 IDisposable 。这使抽象的任何消费者摆脱了是否应该调用 Dispose 的疑问(因为没有 Dispose 调用抽象的方法。)



因为仅实现实现了 IDisposable ,而只有您的组合根创建了此实现,是组成根,负责其处置。万一您的DI容器创建了此资源,它也应该处置它。 Autofac实际上会为您执行此操作。您可以轻松地验证这一点。如果您在不使用DI容器的情况下连接对象图(又名纯DI ),这意味着您必须自己处理合成根中的那些对象。



请注意,此设计更改使您的代码更简单。在抽象上实现 IDisposable 并让消费者处置其依赖项将导致 IDisposable 像病毒一样在您的系统中传播并污染您的代码库。它散布开来,因为对于任何抽象,您始终可以想到需要清理其资源的实现,因此您将必须在每个抽象上实现 IDisposable 。这意味着每个采用一个或多个依赖项的实现也都必须实现 IDisposable ,这会层叠对象图。这会给系统中的每个类增加很多代码,并增加不必要的复杂性。


I'm a little bit confused about Dispose() methods in IDisposable implementations with Autofac usage

Say I have a certain depth to my objects:

  • Controller depends on IManager;
  • Manager depends on IRepository;
  • Repository depends on ISession;
  • ISession is IDisposable.

This leads to the following object graph:

new Controller(
    new Manager(
        new Repository(
            new Session())));

Do I need to make my Manager and Repository implement IDisposable as well and call Manager.Dispose() in Controller, Repository.Dispose() in Manager, etc. or will Autofac automagically know which objects in my call stack properly need to be disposed? Controller object is already IDisposable as it derives from base ASP.NET Web API controller

解决方案

The general rule of resources is that:

He who owns the resource is responsible of disposing of it.

This means that if a class owns a resource, it should either dispose of it in the same method that it created it in (in which case the disposable is called an ephemeral disposable), or if that’s not possible, this generally means that the owning class must implement IDisposable, so it can dispose of the resource in its Dispose method.

But it is important to note that, in general, a class should only own a resource if it is responsible of its creation. But when a resource is injected, this means that this resource already existed before the consumer did. The consumer didn't create the resource and should in that case not dispose of it. Although you can pass on the ownership of the resource to the consumer (and communicate this in the class’s documentation that ownership is passed on), in general you should not pass on the ownership, because this complicates your code and makes the application very fragile.

Although the strategy of transferring ownership of objects might make sense in some cases, for instance for types that are part of a reusable API (like System.IO.StreamReader), it is always bad when dealing with components that are part of your object graph (our so called injectables). I’ll explain why below.

So even if your Controller depends on dependencies that need to be disposed of, your controller should not dispose of them:

  • Because the consumer did not create such dependency, it has no idea what the expected lifetime of its dependency is. It could be very well that the dependency should outlive the consumer. Letting the consumer dispose of that dependency will in that case cause a bug in your application, because the next controller will get an already disposed of dependency, and this will cause an ObjectDisposedException to be thrown.
  • Even if the lifestyle of the dependency equals that of the consumer, disposing is still a bad idea, because this prevents you from easily replacing that component for one that might have a longer lifetime in the future. Once you replace that component for a longer-lived component, you will have to go through all it consumers, possibly causing sweeping changes throughout the application. In other words, you will be violating the Open/closed principle by doing that–it should be possible to add or replace functionality without making sweeping changes instead.
  • If your consumer is able to dispose of its dependency, this means that you implement IDisposable on that abstraction. This means this abstraction is leaking implementation details–that’s a violation of the Dependency Inversion Principle. You are leaking implementation details when implementing IDisposable on an abstraction, because it is very unlikely that every implementation of that abstraction needs deterministic disposal and so you defined the abstraction with a certain implementation in mind. The consumer should not have to know anything about the implementation, whether it needs deterministic disposal or not.
  • Letting that abstraction implement IDisposable also causes you to violate the Interface Segregation Principle, because the abstraction now contains an extra method (i.e. Dispose), that not all consumers need to call. They might not need to call it, because –as I already mentioned– the resource might outlive the consumer. Letting it implement IDisposable in that case is dangerous, because anyone can call Dispose on it causing the application to break. If you are more strict about testing, this also means you will have to test a consumer for not calling the Dispose method. This will cause extra test code. This is code that needs to be written and maintained.

So instead, you should only let the implementation implement IDisposable. This frees any consumer of the abstraction from the doubts whether it should or shouldn't call Dispose (because there is no Dispose method to call on the abstraction).

Because only the implementation implements IDisposable and only your Composition Root creates this implementation, it is the Composition Root that is responsible of its disposal. In case your DI container creates this resource, it should also dispose it. Autofac will actually do this for you. You can easily verify this. In case you wire your object graphs without the use of a DI Container (a.k.a. Pure DI), it means that you will have to dispose of those objects in your Composition Root yourself.

Note that this design change makes your code simpler. Implementing IDisposable on the abstraction and letting consumers dispose of their dependencies will cause IDisposable to spread out through your system like a virus and pollutes your code base. It spreads out, because for any abstraction, you can always think of an implementation that needs to clean up its resources, so you will have to implement IDisposable on every abstraction. This means that every implementation that takes one or more dependencies will also has to implement IDisposable as well, and this cascades up the object graph. This adds a lot of code and unnecessary complexity to each class in your system.

这篇关于依赖注入和IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆