我要注册两次课,但合同不同。
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似乎无法完成任何这些任务。有办法解决吗?
答案 0 :(得分:5)
在应用程序关闭时将调用Dispose方法。但是由于已注册两次,因此将被调用两次。 。 。有解决的办法吗?
是的。问题出在您的IDisposable实现中:
如果多次调用对象的Dispose方法,则该对象 必须忽略第一个之后的所有呼叫。物体不能扔 如果其Dispose方法被多次调用,则为异常。实例 除Dispose之外的其他方法在以下情况下可能引发ObjectDisposedException: 资源已被处置。