如何确保不处置其他人仍在使用的对象 [英] How to make sure not to dispose objects that are still used by others

查看:52
本文介绍了如何确保不处置其他人仍在使用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用构造函数注入的类。

I have a class that use constructor injections.

public class MyClass
{                       
    public MyClass(IInterface1 interface1)
    {            
    }

    public Dispose()
    {
       interface1.dispose();
    }
}

interface1将由DI注入。但是有时候,我需要手动创建MyClass。

interface1 will be injected by DI. But sometimes, i need to create MyClass manually.

public class MyOtherClass
{                       
    private readonly IInterface1 _interface1;

    public MyOtherClass()
    {
      _interface1 = new Interface1();
    }       

    public Foo()
    {
       foo = new MyClass(_interface1);
       bar = new MyClass(_interface1);
    }
}

在我的dispose方法中,当MyClass时,interface1总是被废弃被摧毁。问题是,interface1由MyOtherClass拥有,并且可能仍由其他实例使用,不应丢弃。我该如何解决?

in my dispose method, interface1 is always disposed when MyClass is destroyed. The problem is, interface1 is own by MyOtherClass and might still be used by other instances and shouldn't be disposed. How can i resolve this?

推荐答案

您不应致电

interface1.dispose();

在MyClass内部。

inside MyClass.

如果interface1是由DI容器创建的对象,将被释放到该容器中。
如果要像在MyOtherClass中一样显式创建它,请将其放在MyOtherClass中。

If interface1 is created by the DI container, it will be rleased there. If you are creating it explicitly as in MyOtherClass, Dispose it in MyOtherClass.

这篇关于如何确保不处置其他人仍在使用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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