处理由Microsoft DependencyInjection多次调用

All*_*est 2 c# dependency-injection autofac asp.net-core

我正在两次注册课程,但签订了不同的合同.

services
    .AddSingleton<MyClass>()
    .AddSingleton<IHostedService>(sp => sp.GetService<MyClass>());
Run Code Online (Sandbox Code Playgroud)

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

Autofac有两种解决方法:

builder.RegisterType<MyClass>().AsSelf().As<IHostedService>();
//or
builder.RegisterType<MyClass>().AsSelf();
builder.Register(ctx => ctx.Resolve<MyClass>()).As<IHostedService>().ExternallyOwned();
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*oft 5

应用程序关闭时将调用Dispose方法.但由于它已注册两次,因此会被调用两次...有没有办法解决呢?

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

如果多次调用对象的Dispose方法,则该对象必须忽略第一个之后的所有调用.如果多次调用Dispose方法,则该对象不得抛出异常.除了Dispose之外的实例方法可以在已经处置资源时抛出ObjectDisposedException.

IDisposable.Dispose

  • 这表明行为_should_不是问题.但是假设你正在处理来自第三方的写得不好的Dispose()? (2认同)