问题描述
我终于包装我的头在C#中周围的IoC和DI,并正与一些边缘挣扎。我使用的是统一的容器,但我认为这个问题的适用范围更广。
I'm finally wrapping my head around IoC and DI in C#, and am struggling with some of the edges. I'm using the Unity container, but I think this question applies more broadly.
使用IoC容器来分配的实现IDisposable乐不可支实例!怎么是你应该知道,如果你要的Dispose()?该实例可能已创建只为你(并为此你应该Dispose()方法的话),或者它可能是一个实例,其使用寿命在别处管理(并为此你最好不要)。在code没有告诉你,事实上,这可能会改变的基础上配置!这似乎是致命的给我。
Using an IoC container to dispense instances that implement IDisposable freaks me out! How are you supposed to know if you should Dispose()? The instance might have been created just for you (and therefor you should Dispose() it), or it could be an instance whose lifetime is managed elsewhere (and therefor you'd better not). Nothing in the code tells you, and in fact this could change based on configuration!!! This seems deadly to me.
能否任何IoC的专家那里说明良好的方式来处理这个歧义?
Can any IoC experts out there describe good ways to handle this ambiguity?
推荐答案
。
AutoFac handles this by allowing the creation of a nested container. When the container is finished with, it automatically disposes of all IDisposable objects within it. More here.
..当你解决服务,Autofac会跟踪解决一次性(IDisposable接口)组件。的在工作单位的最后,你处理相关的寿命范围和Autofac会自动清理解决服务/处置。的
这篇关于你如何调和IDisposable接口和IOC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!