奇怪的问题。如果您关注的是具体IDisposable
,大多数容器将检查落实,如果它包含的IDisposable
实现容器将调用Dispose()
自动神奇时,它释放的实例。
所以,
// pure clean business interface. no dispose member
public interface ISomeBusinessInterface { }
// an implementation that does not require any 'disposing'
// and implements *only* business interface
public class SomeBusinessImplementation :
ISomeBusinessInterface
{
}
// an implementation that contains heavy resources and
// requires 'disposing'
public class SomeDisposableBusinessImplementation :
ISomeBusinessInterface,
IDisposable
{
}
// a typical consumer. no knowledge of instance life-cycle
public class SomeConsumer
{
// injector constructor
public SomeConsumer (ISomeBusinessInterface business) { }
}
你的消费者应该没有注入组件生命周期的知识,并且不以任何方式形状或形式负责。从这个角度来看,ISomeBusinessInterface
不会继承或暴露任何这样的方法 - 我的意思是,考虑你是否处置了一个重要的单例服务!这会有多尴尬?
那么谁来负责注入组件的生命周期呢?那么容器当然是!如前所述,大多数容器将检查组件实现为IDisposable
实现[也另一个理由使用标准CLR定义的接口],和将调用Dispose
当它确定部件已经到达其寿命的终点。所以SomeDisposableBusinessImplementation
最终会妥善处置。 :)
温莎城堡
温莎城堡IoC容器的轨道,并保持它创建的所有实例的引用。它使用反射来确定实例是否“一次性”,然后在实例的生命周期完成时调用Dispose()
。对于长寿命的物体,这是容器被丢弃的时候。对于短暂的短暂对象,这是消费者*明确调用Release (object)
时的情况。
* =这提出了一个重要的点,瞬态对象应通过明确呼吁Resolve<T>()
并通过显式调用Release (object)
获得。隐式注入瞬态类可能会导致内存泄漏!
StructureMap
StructureMap IoC container does not track and maintain references to transient instances.还几乎手段对象生命周期管理是一个有点复杂+。这对短暂的短暂物体非常有用,因为不需要额外记帐except the usual。但是,对于长寿命的对象,您必须使用extend the framework, reflect, and dispose of instances yourself。
+ =复杂的imo。
我在发生错误时专门清理了一些事件处理程序。我基本上想关闭一些在后台运行的类。我想可以使用自定义的生命周期,让我手动关闭类的按需。我正在使用Structuremap。 – 2009-12-22 16:14:03