IDisposable的实现非IDisposable接口的接口、IDisposable

2023-09-05 01:42:33 作者:本是荒野客

什么是正确与界面的默认实现处理时,在接口不自IDisposable继承的最佳方法是什么?例如,假设我想做的事情

 公共类FooGetter:IDisposable的{

    私人IFooProvider fooProvider = MyContainer.GetDefault&其中; IFooProvider>();
    ...
    公共无效的Dispose(){
         ...
         如果(!fooProvider = NULL)fooProvider.Dispose(); //显然这里编译出错
    }
}
 

和它只是恰巧,IFooProvider的默认实现了IDisposable,但IFooProvider接口不自IDisposable继承。如何/我在哪里应该处理它?

现在的问题不只是依赖注入容器;这也适用于一个紧密耦合的依赖关系:

 私人IFooProvider fooProvider =新PatrickProvider();
 

在这种情况下,我可以保持另一个参考,这样我可以在以后的Dispose(),但似乎真的janky:

 私人PatrickProvider defaultFooProvider =新PatrickProvider();
私人IFooProvider fooProvider = defaultFooProvider;
 
非富二代慎入 华硕神级显卡售14888元

寻找这里最好的(或好)的做法。

解决方案

在使用DI容器就是让你的DI容器处理对象的生命周期为你的最佳做法。这是不可能的,如果你用你的DI容器作为服务定位器(嘘!反模式!!),就像你似乎与 MyContainer.GetDefault 做,但如果你有正确的通过构造函数注入注入你的依赖,那么它会工作得很好。

有关紧耦合的依赖,你就必须做一些愚蠢的像

 使用(fooProvider为IDisposable接口)
{
    //使用fooProvider code
}
 

我认为(但我不能100%确定)的使用如果通过会做什么,所以这将工作与否 fooProvider 工具的IDisposable

还有就是的IDisposable ,因为它涉及到依赖性的DI马克塞曼的的 依赖注入.NET 的的第8章。

What is the best way to properly deal with a default implementation of a interface when the interface doesn't inherit from IDisposable? For example, suppose I want to do

public class FooGetter : IDisposable {

    private IFooProvider fooProvider = MyContainer.GetDefault<IFooProvider>();
    ...
    public void Dispose(){
         ...
         if (fooProvider != null) fooProvider.Dispose(); // obviously has compile error here
    }
}

And it just so happens that the default implementation of IFooProvider is IDisposable, but IFooProvider interface does not inherit from IDisposable. How/where am I supposed to dispose of it?

The question isn't just for dependency injection containers; it would also apply to a tightly-coupled dependency:

private IFooProvider fooProvider = new PatrickProvider();

In this case, I could keep another reference so that I can later Dispose() it, but that seems really janky:

private PatrickProvider defaultFooProvider = new PatrickProvider();
private IFooProvider fooProvider = defaultFooProvider;

Looking for best (or good) practices here.

解决方案

Best practices when using a DI container is to let your DI container handle the lifetime of the object for you. This is not possible if you use your DI container as a service locator (boo! anti-pattern!!), like you seem to be doing with MyContainer.GetDefault, but if you properly have your dependencies injected through constructor injection, then it would work well.

For tightly-coupled dependencies, you would have to do something stupid like

using(fooProvider as IDisposable)
{
    // Code that uses fooProvider
}

I think (but am not 100% sure) that using will do nothing if passed null, so this will work whether or not fooProvider implements IDisposable.

There is a good discussion of IDisposable as it relates to dependencies an DI in Mark Seemann's Dependency Injection in .NET chapter 8.

 
精彩推荐
图片推荐