Scoped services disposed twice
anpete opened this issue · comments
Consider:
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleApp1
{
public interface IMyService
{
}
public class MyService : IMyService, IDisposable
{
public static int DisposeCount;
public void Dispose()
{
DisposeCount++;
}
}
public class Program
{
public static void Main()
{
var services = new ServiceCollection()
.AddScoped<IMyService>(provider => provider.GetService<MyService>())
.AddScoped<MyService, MyService>()
.BuildServiceProvider();
var scope = services.CreateScope();
var service = scope.ServiceProvider.GetService<IMyService>();
scope.Dispose();
Console.WriteLine(MyService.DisposeCount); // Count == 2
}
}
}
Dispose is called twice on the service, presumably because of the multiple registrations. Is this by-design?
Yes this is by design. There's no way to opt out of dispose for factories(the lambda). Did you intend to make DisposeCount static?
Thanks for the confirmation. Re static, yeah, it was late.