Add a test to verify our service lifetimes

This test uses the new features in the service provider to verify that we
don't reference any scoped services from singletons.

Note that this can't really cover the cases where we have optional
services or where we replace default services (like DI for controllers).
You'll just have to be careful.
This commit is contained in:
Ryan Nowak 2016-07-20 16:52:22 -07:00
parent bc76c0ef31
commit b80f4d31f3
2 changed files with 30 additions and 2 deletions

View File

@ -7,8 +7,6 @@ using System.Linq;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Routing;

View File

@ -33,6 +33,8 @@ using Moq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using Xunit;
using Microsoft.Extensions.ObjectPool;
using System.Diagnostics;
namespace Microsoft.AspNetCore.Mvc
{
@ -245,6 +247,34 @@ namespace Microsoft.AspNetCore.Mvc
Assert.Single(services, d => d.ServiceType == typeof(IConfigureOptions<MvcJsonOptions>));
}
[Fact]
public void AddMvc_NoScopedServiceIsReferredToByASingleton()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<IHostingEnvironment>(GetHostingEnvironment());
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.AddSingleton<DiagnosticSource>(new DiagnosticListener("Microsoft.AspNet"));
services.AddLogging();
services.AddOptions();
services.AddMvc();
var root = services.BuildServiceProvider(validateScopes: true);
var scopeFactory = root.GetRequiredService<IServiceScopeFactory>();
// Act & Assert
using (var scope = scopeFactory.CreateScope())
{
foreach (var serviceType in services.Select(d => d.ServiceType).Where(t => !t.GetTypeInfo().IsGenericTypeDefinition).Distinct())
{
// This will throw if something is invalid.
scope.ServiceProvider.GetService(typeof(IEnumerable<>).MakeGenericType(serviceType));
}
}
}
private IEnumerable<Type> SingleRegistrationServiceTypes
{
get