依赖注入 - 如果依赖的寿命短于依赖对象?对象、寿命短

2023-09-03 20:42:10 作者:妑莂亾哋傷裝洎己茬囗袋

我认识到,DI是一个非常灵活的设计模式,但我在努力接受它作为我的'尚方宝剑'创建脱钩code。

I realise that DI is a very flexible design pattern, although I'm struggling to accept it as my 'silver bullet' for creating decoupled code.

这里的原因:当依赖对象具有更长的寿命比它被注射了

Here's why: What happens when the dependent object has a longer lifetime than the dependencies it has been injected with?

示例应用程序:我有一个实例化我的应用程序的生命周期一个 BusinessLogic 类。这个类需要一个的DataContext 对象执行数据库操作。我有thefore创建了一个抽象的 DataContextFactory 有两种实现方式: StaticDataContextFactory WebDataContextFactory 。前者保持应用程序的生命周期的单一DataContext的,而后者将创造新的DataContexts为每个HTTP请求。​​

Example application: I have a BusinessLogic class which is instantiated for the lifetime of my application. This class requires a DataContext object to perform database operations. I have thefore created an abstract DataContextFactory with two implementations: StaticDataContextFactory and WebDataContextFactory. The former maintains a single DataContext for the lifetime of the application, whereas the latter will create new DataContexts for each HTTP request.

在这个例子中的问题:正如你所看到的,一切都会好起来的时候 StaticDataContextFactory 被使用。然而,当 WebDataContextFactory 使用了 BusinessLogic 将失败,因为它注入了一个的DataContext 将到期/处置一旦第一个请求完成。

Problem in the example : As you can see, all will be fine when the StaticDataContextFactory is used. However, when the WebDataContextFactory is used the BusinessLogic will fail, since it's injected with a DataContext which will expire/dispose once the first request completes.

我的问题是:都必须依赖对象有一生的时间是小于或等于其依赖的生命周期?如果是这样,当每一个依赖的生存期是未知的code的实例化相关的类,然后会发生什么?

My question is: Must all dependent objects have a lifetime which is less or equal to the lifetime of its dependencies? If so, then what happens when the lifetime of each dependency is unknown to the code which instantiates the dependent classes?

推荐答案

Spring框架的Web集成使用的地址和代理方面的这个问题。更长范围的对象是注入代理较短范围的对象。每个代理知道如何(为会话级和请求范围豆分别)获取当前版本的短范围的委托,通过HTTP会话或HTTP请求。​​

The Spring framework's web integration addresses this problem using proxies and aspects. Longer-scoped objects are injected with proxies to the shorter-scoped objects. Each proxy knows how to fetch the "current" version of its shorter-scoped delegate, via the HTTP session or HTTP request (for session- and request-scoped beans, respectively).

请参阅http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes-other-injection