控制反转和RAII可以一起玩吗? [英] Can inversion of control and RAII play together?

查看:93
本文介绍了控制反转和RAII可以一起玩吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了控制反转(IOC),这使我感到困扰,似乎这使内存管理很痛苦.当然,似乎ioc主要用于垃圾收集环境(Net,Java,脚本),而我担心的是非gc设置.

I was just reading up on inversion of control (IOC) and it bothered me that it seems like it makes memory management a pain. Of course it seems ioc is mostly used in garbage collected environments (Net,Java,Scripting), while my concern is in non-gc settings.

我在这里担心的是,IOC在某种程度上与RAII背道而驰,因为我们将资源生存期与对象生存期脱钩了.这样增加的复杂性难道不会困扰其他任何人吗?真正的问题是,可以使用哪些技术使事情顺利进行?

My concern here is that IOC in a way goes against RAII, as we decouple resource lifetime from object lifetime. Doesn't this added complexity bother anyone else? And the real question, what techniques can be used to make things go smoothly?

推荐答案

由于这个原因,我制作了自己的IoC容器,该容器返回(在C#/.NET中)一次性服务包装,该容器在处理后将关于服务的正确选择.

For this very reason I've made my own IoC container which returns (in C#/.NET) disposable service wrappers, that when disposed of, will "do the right thing" in regards to the service.

就这样:

  • 在以下情况下不执行任何操作:
    • 该对象未实现IDisposable
    • 不是容器范围的(在这种情况下,容器将跟踪它并多次返回相同的对象,并且当容器被处置时,该对象也将是容器)
    • 未合并
    • 它不是单例作用域(与容器作用域相同,但是容器的层次结构会将单例作用域的服务存储在最顶层的容器中)
    • Do nothing, when:
      • The object does not implement IDisposable
      • Is not container-scoped (in which case the container will keep track of it and return the same object more than once, and when the container is disposed of, the object will be too)
      • It is not pooled
      • It is not singleton-scoped (same as container-scoped, but a hierarchy of containers will store the singleton-scoped service in the topmost container)

      这意味着所有使用我的服务的代码都在using-block内,但目的至少对于我来说更清楚:

      This means that all code that uses my services is inside a using-block, but the intent is more clear, at least to me:

      using (var service = container.Resolve<ISomeService>())
      {
          service.Instance.SomeMethod();
      }
      

      基本上说:解析服务,在服务实例上调用SomeMethod,然后处置该服务.

      basically it says: resolve a service, call SomeMethod on the service instance, and then dispose of the service.

      由于消费者不知道是否要废弃服务实例,因此可以选择完全忽略IDisposable实现,或者废弃所有实现IDisposable的服务.对我来说,这都不是一个好的解决方案.第三种选择是将服务实例包装在一个对象中,该对象一旦处理了包装器,便知道如何处理该服务.

      Since knowledge of whether to dispose of the service instance or not isn't available to the consumer, there was either the choice of just ignoring IDisposable implementations altogether, or to dispose of all services which implement IDisposable. Neither was a good solution to me. The third choice was to wrap the service instance in an object that knew what to do with the service once the wrapper was disposed of.

      这篇关于控制反转和RAII可以一起玩吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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