gpt4 book ai didi

c# - 为什么 autofac 双重处理我的一次性用品?

转载 作者:行者123 更新时间:2023-11-30 13:10:35 26 4
gpt4 key购买 nike

嗨,这对我来说似乎是错误的。这是它的设计方式吗?

我的一次性类(class):

class C : IDisposable
{
public void Dispose()
{
Console.WriteLine("Disposing C");
}
}

注册:

cb.RegisterInstance(new C());

用法:

using (IContainer container = BuildContainer())
{
var c = container.Resolve<C>();
Console.WriteLine("C resolved");
}

输出:

C resolved
Disposing C
Disposing C

我认为对同一个对象多次调用 Dispose 是一件坏事。

注意:当我这样注册类(class)时

cb.Register(c => new C());

它只会被处理一次。为什么不同?

最佳答案

I think its a bad thing to call Dispose multiple times on the same object.

不是,Dispose多次调用应该是安全的。来自文档:"The object must not throw an exception if its Dispose method is called multiple times."因为这应该是安全的,所以您不应该依赖其他库只调用它一次,并且您认为不应该产生影响的更改没有任何问题导致多个 Dispose电话。

关于c# - 为什么 autofac 双重处理我的一次性用品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com