gpt4 book ai didi

c# - Dispose 被 Microsoft DependencyInjection 多次调用

转载 作者:行者123 更新时间:2023-12-03 22:18:03 28 4
gpt4 key购买 nike

我注册了两次类(class),但契约(Contract)不同。

services
.AddSingleton<MyClass>()
.AddSingleton<IHostedService>(sp => sp.GetService<MyClass>());

该类还实现了 IDisposable这意味着将在应用程序关闭时调用 Dispose 方法。但是由于它被注册了两次,所以它会被调用两次。

Autofac 有两种方法可以解决这个问题:
builder.RegisterType<MyClass>().AsSelf().As<IHostedService>();
//or
builder.RegisterType<MyClass>().AsSelf();
builder.Register(ctx => ctx.Resolve<MyClass>()).As<IHostedService>().ExternallyOwned();

但似乎无法在 ASP.NET Core 中使用 Microsoft DependencyInjection 执行任何操作。有办法解决吗?

最佳答案

Dispose method will be called on application shutdown. But since it's registered twice, it will be called twice. . . .Is there a way to solve it?



是的。问题出在您的 IDisposable 实现中:

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.



IDisposable.Dispose

关于c# - Dispose 被 Microsoft DependencyInjection 多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51912628/

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