Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Breaking change: Throw when resolving on a disposed service provider #45116

Merged
merged 18 commits into from
Dec 4, 2020
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ internal class ServiceProviderEngineScope : IServiceScope, IServiceProvider, IAs
private List<object> _disposables;

private bool _disposed;
private readonly object _lock = new object();
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved

public ServiceProviderEngineScope(ServiceProviderEngine engine)
{
Expand All @@ -41,17 +42,28 @@ public object GetService(Type serviceType)

internal object CaptureDisposable(object service)
{
Debug.Assert(!_disposed);

_captureDisposableCallback?.Invoke(service);

if (ReferenceEquals(this, service) || !(service is IDisposable || service is IAsyncDisposable))
{
return service;
}

lock (ResolvedServices)
lock (_lock)
{
if (_disposed)
{
if (service is IDisposable disposable)
{
disposable.Dispose();
}
else
{
// sync over async, for the rare case that an object only implements IAsyncDisposable and may end up starving the thread pool.
Task.Run(() => ((IAsyncDisposable)service).DisposeAsync().AsTask()).GetAwaiter().GetResult();
}
ThrowHelper.ThrowObjectDisposedException();
}
if (_disposables == null)
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
{
_disposables = new List<object>();
Expand Down Expand Up @@ -144,7 +156,7 @@ static async ValueTask Await(int i, ValueTask vt, List<object> toDispose)
private List<object> BeginDispose()
{
List<object> toDispose;
lock (ResolvedServices)
lock (_lock)
{
if (_disposed)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

<ItemGroup>
<Compile Include="..\DI.Specification.Tests\**\*.cs" />
<Compile Include="$(CommonPath)..\tests\Extensions\SingleThreadedSynchronizationContext.cs"
Link="Shared\SingleThreadedSynchronizationContext.cs" />
</ItemGroup>

<ItemGroup>
Expand All @@ -15,4 +17,8 @@
<ProjectReference Include="..\..\src\Microsoft.Extensions.DependencyInjection.csproj" SkipUseReferenceAssembly="true" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net461'">
<PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection.Fakes;
using Microsoft.Extensions.DependencyInjection.Specification;
using Microsoft.Extensions.DependencyInjection.Specification.Fakes;
using Microsoft.Extensions.DependencyInjection.Tests.Fakes;
using Microsoft.Extensions.Internal;
using Xunit;

namespace Microsoft.Extensions.DependencyInjection.Tests
Expand Down Expand Up @@ -265,6 +267,128 @@ public void ScopeDispose_PreventsServiceResolution()
Assert.NotNull(provider.CreateScope());
}

[Fact]
public void GetService_ThenDisposeOnDifferentThread_ServiceDisposed()
{
var services = new ServiceCollection();
services.AddSingleton<Foo1>();
IServiceProvider sp = services.BuildServiceProvider();
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
var foo = sp.GetRequiredService<Foo1>();
Task.Run(() => (sp as IDisposable).Dispose()).Wait();
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved

Assert.True(foo.IsDisposed);
}

[Fact]
public void GetService_DisposeOnSameThread_Throws()
{
var services = new ServiceCollection();
services.AddSingleton<Foo2>();
IServiceProvider sp = services.BuildServiceProvider();
Assert.Throws<ObjectDisposedException>(() =>
{
// ctor disposes ServiceProvider
var foo = sp.GetRequiredService<Foo2>();
});
}

[Fact]
public void GetAsyncService_DisposeAsyncOnSameThread_ThrowsAndDoesNotHang()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<FooAsyncDisposable>();
var sp = services.BuildServiceProvider();
bool success = Task.Run(() =>
{
SingleThreadedSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() =>
{
// Act
Assert.Throws<ObjectDisposedException>(() =>
{
// ctor disposes ServiceProvider
var foo = sp.GetRequiredService<FooAsyncDisposable>();
});
},
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext()
).Wait();
});
}).Wait(TimeSpan.FromSeconds(10));
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved

Assert.True(success);
}

private class Foo1 : IDisposable
{
public Foo1()
{
Thread.Sleep(5000);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this testing?

Copy link
Member Author

@maryamariyan maryamariyan Dec 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If during resolve of this service, service provider gets disposed on another thread, the test asserts that we dispose of the service as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But the way the test is written above, this sleep will happen inline and then the object will be returned on line 276.

Once the object is returned, then you are starting a new thread to dispose the service provider.

So I don't think the sleep is doing anything beneficial.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, we need to kick off 2 threads.

Copy link
Member Author

@maryamariyan maryamariyan Dec 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If during resolve of this service, service provider gets disposed on another thread, the test asserts that we dispose of the service as well.

Removed this test and instead used tests below to also assert that the service (for both IDisposable and IAsyncDisposable cases) get disposed:

  • GetAsyncService_DisposeAsyncOnSameThread_ThrowsAndDoesNotHangAndDisposeAsyncGetsCalled
  • GetService_DisposeOnSameThread_ThrowsAndDoesNotHangAndDisposeGetsCalled

The removed case would have been very similar in outcome to the two test cases I mentioned above, so perhaps OK that we don't add it.

}
public bool IsDisposed { get; private set; }

public void Dispose()
{
IsDisposed = true;
}
}

private class Foo2 : IDisposable
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
{
public Foo2(IServiceProvider sp)
{
(sp as IDisposable).Dispose();
}
public void Dispose() { }
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task AddDisposablesAndAsyncDisposables_DisposeAsync_AllDisposed(bool includeDelayedAsyncDisposable)
{
var services = new ServiceCollection();
services.AddSingleton<AsyncDisposable>();
services.AddSingleton<Disposable>();
if (includeDelayedAsyncDisposable)
{
//forces Dispose ValueTask to be asynchronous and not be immediately completed
services.AddSingleton<DelayedAsyncDisposableService>();
}
ServiceProvider sp = services.BuildServiceProvider();
var disposable = sp.GetRequiredService<Disposable>();
var asyncDisposable = sp.GetRequiredService<AsyncDisposable>();
DelayedAsyncDisposableService delayedAsyncDisposableService = null;
if (includeDelayedAsyncDisposable)
{
delayedAsyncDisposableService = sp.GetRequiredService<DelayedAsyncDisposableService>();
}

await sp.DisposeAsync();

Assert.True(disposable.Disposed);
Assert.True(asyncDisposable.DisposeAsyncCalled);
if (includeDelayedAsyncDisposable)
{
Assert.Equal(1, delayedAsyncDisposableService.DisposeCount);
}
}

private class FooAsyncDisposable : IFakeService, IAsyncDisposable
maryamariyan marked this conversation as resolved.
Show resolved Hide resolved
{
public FooAsyncDisposable(IServiceProvider sp)
{
(sp as IDisposable).Dispose();
}
public async ValueTask DisposeAsync()
{
await Task.Yield();
}
}

[ActiveIssue("https://github.com/dotnet/runtime/issues/42160")] // We don't support value task services currently
[Theory]
[InlineData(ServiceLifetime.Transient)]
Expand Down