Skip to content

Commit

Permalink
Issue aspnet#347: Throw a better exception when the user didn't add t…
Browse files Browse the repository at this point in the history
…he MVC services.

Introducing MarkerService for identifying if MvcServices were added.
  • Loading branch information
sornaks committed Aug 21, 2014
1 parent eccd25b commit 791518d
Show file tree
Hide file tree
Showing 16 changed files with 285 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Mvc.sln
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "ConnegWebsite", "test\WebSi
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AntiForgeryWebSite", "test\WebSites\AntiForgeryWebSite\AntiForgeryWebSite.kproj", "{A353B17E-A940-4CE8-8BF9-179E24A9041F}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AddServicesWebSite", "test\WebSites\AddServicesWebSite\AddServicesWebSite.kproj", "{6A0B65CE-6B01-40D0-840D-EFF3680D1547}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -362,6 +364,16 @@ Global
{A353B17E-A940-4CE8-8BF9-179E24A9041F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{A353B17E-A940-4CE8-8BF9-179E24A9041F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{A353B17E-A940-4CE8-8BF9-179E24A9041F}.Release|x86.ActiveCfg = Release|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Debug|x86.ActiveCfg = Debug|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Release|Any CPU.Build.0 = Release|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{6A0B65CE-6B01-40D0-840D-EFF3680D1547}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -396,5 +408,6 @@ Global
{EE1AB716-F102-4CA3-AD2C-214A44B459A0} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{C6E5AFFA-890A-448F-8DE3-878B1D3C9FC7} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{A353B17E-A940-4CE8-8BF9-179E24A9041F} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{6A0B65CE-6B01-40D0-840D-EFF3680D1547} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
EndGlobalSection
EndGlobal
13 changes: 13 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/Internal/MvcMarkerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

namespace Microsoft.AspNet.Mvc.Internal
{
/// <summary>
/// This is a Marker class which is used to determine if all the services were added
/// to when Mvc is loaded.
/// </summary>
public class MvcMarkerService
{
}
}
30 changes: 30 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/Internal/MvcServicesHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.Framework.DependencyInjection;

namespace Microsoft.AspNet.Mvc.Internal
{
/// <summary>
/// Helper class which contains MvcServices related helpers.
/// </summary>
public static class MvcServicesHelper
{
/// <summary>
/// Throws InvalidOperationException when MvcMarkerService is not present
/// in the list of services.
/// </summary>
/// <param name="services">The list of services.</param>
/// <param name="serviceType">The type of service which needs to be searched for.</param>
public static void ThrowIfMvcNotRegistered(IServiceProvider services)
{
if (services.GetServiceOrNull(typeof(MvcMarkerService)) == null)
{
throw new InvalidOperationException(Resources.FormatUnableToFindServices(
"IServiceCollection.AddMvc()", "IBuilder.UseServices(...)", "IBuilder.UseMvc(...)"));
}
}
}
}
6 changes: 6 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/MvcRouteHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
Expand All @@ -31,6 +32,11 @@ public string GetVirtualPath([NotNull] VirtualPathContext context)
public async Task RouteAsync([NotNull] RouteContext context)
{
var services = context.HttpContext.RequestServices;

// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(services);

Contract.Assert(services != null);

// TODO: Throw an error here that's descriptive enough so that
Expand Down
16 changes: 16 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -354,4 +354,7 @@
<data name="RouteConstraintAttribute_InvalidKeyHandlingValue" xml:space="preserve">
<value>The value must be either '{0}' or '{1}'.</value>
</data>
<data name="UnableToFindServices" xml:space="preserve">
<value>Unable to find the required services. Please add all the required services by calling '{0}' inside the call to '{1}' or '{2}' in the application startup code.</value>
</data>
</root>
5 changes: 5 additions & 0 deletions src/Microsoft.AspNet.Mvc/BuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.Routing;
using Microsoft.AspNet.Routing;

Expand All @@ -24,6 +25,10 @@ public static IBuilder UseMvc([NotNull] this IBuilder app)

public static IBuilder UseMvc([NotNull] this IBuilder app, [NotNull] Action<IRouteBuilder> configureRoutes)
{
// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

var routes = new RouteBuilder
{
DefaultHandler = new MvcRouteHandler(),
Expand Down
3 changes: 3 additions & 0 deletions src/Microsoft.AspNet.Mvc/MvcServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.OptionDescriptors;
using Microsoft.AspNet.Mvc.Razor;
Expand Down Expand Up @@ -117,6 +118,8 @@ public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration
typeof(HtmlHelper<>),
implementationInstance: null,
lifecycle: LifecycleKind.Transient);

yield return describe.Transient<MvcMarkerService, MvcMarkerService>();
}
}
}
45 changes: 45 additions & 0 deletions src/Microsoft.AspNet.Mvc/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Internal;
using Moq;
using Xunit;

namespace Microsoft.AspNet.Mvc
{
public class MvcServicesHelperTests
{
[Fact]
public void MvcServicesHelperThrowsIfServiceIsAbsent()
{
// Arrange
var services = new Mock<IServiceProvider>();
services.Setup(o => o.GetService(typeof(IEnumerable<MvcMarkerService>)))
.Returns(new List<MvcMarkerService>());
var expectedMessage = "Unable to find the required services. Please add all the required " +
"services by calling 'IServiceCollection.AddMvc()' inside the call to 'IBuilder.UseServices(...)' " +
"or 'IBuilder.UseMvc(...)' in the application startup code.";

// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(
() => MvcServicesHelper.ThrowIfMvcNotRegistered(services.Object));
Assert.Equal(expectedMessage, ex.Message);
}

[Fact]
public void MvcServicesHelperDoesNotThrowIfServiceExists()
{
// Arrange
var services = new Mock<IServiceProvider>();
var expectedOutput = new MvcMarkerService();
services.Setup(o => o.GetService(typeof(IEnumerable<MvcMarkerService>)))
.Returns(new List<MvcMarkerService> { expectedOutput });

// Act & Assert
Assert.DoesNotThrow(() => MvcServicesHelper.ThrowIfMvcNotRegistered(services.Object));
}
}
}
4 changes: 4 additions & 0 deletions test/Microsoft.AspNet.Mvc.Core.Test/MvcRouteHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
Expand Down Expand Up @@ -192,6 +194,8 @@ private RouteContext CreateRouteContext(
.Returns(invokerFactory);
httpContext.Setup(h => h.RequestServices.GetService(typeof(ILoggerFactory)))
.Returns(loggerFactory);
httpContext.Setup(h => h.RequestServices.GetService(typeof(IEnumerable<MvcMarkerService>)))
.Returns(new List<MvcMarkerService> { new MvcMarkerService() });

return new RouteContext(httpContext.Object);
}
Expand Down
29 changes: 29 additions & 0 deletions test/Microsoft.AspNet.Mvc.FunctionalTests/MvcStartupTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.TestHost;
using Xunit;

namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class MvcStartupTests
{
private readonly IServiceProvider _provider = TestHelper.CreateServices("AddServicesWebSite");
private readonly Action<IBuilder> _app = new AddServicesWebSite.Startup().Configure;

[Fact]
public void MvcThrowsWhenRequiredServicesAreNotAdded()
{
// Arrange
var expectedMessage = "Unable to find the required services. Please add all the required " +
"services by calling 'IServiceCollection.AddMvc()' inside the call to 'IBuilder.UseServices(...)' " +
"or 'IBuilder.UseMvc(...)' in the application startup code.";

// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => TestServer.Create(_provider, _app));
Assert.Equal(expectedMessage, ex.Message);
}
}
}
1 change: 1 addition & 0 deletions test/Microsoft.AspNet.Mvc.FunctionalTests/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
},
"dependencies": {
"ActivatorWebSite": "",
"AddServicesWebSite": "",
"AntiForgeryWebSite": "",
"BasicWebSite": "",
"CompositeViewEngine": "",
Expand Down
31 changes: 31 additions & 0 deletions test/WebSites/AddServicesWebSite/AddServicesWebSite.kproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>6a0b65ce-6b01-40d0-840d-eff3680d1547</ProjectGuid>
<OutputType>Web</OutputType>
</PropertyGroup>
<PropertyGroup Condition="$(OutputType) == 'Console'">
<DebuggerFlavor>ConsoleDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="$(OutputType) == 'Web'">
<DebuggerFlavor>WebDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'" Label="Configuration">
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DevelopmentServerPort>38820</DevelopmentServerPort>
</PropertyGroup>
<Import Project="$(VSToolsPath)\AspNet\Microsoft.Web.AspNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
32 changes: 32 additions & 0 deletions test/WebSites/AddServicesWebSite/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;

namespace AddServicesWebSite
{
public class Startup
{
public void Configure(IBuilder app)
{
var configuration = app.GetTestConfiguration();

// Not calling AddMvc() here.
// The purpose of the Website is to demonstrate that it throws
// when AddMvc() is not called.

// Add MVC to the request pipeline
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute",
"{area:exists}/{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("ActionAsMethod", "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
10 changes: 10 additions & 0 deletions test/WebSites/AddServicesWebSite/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"dependencies": {
"Microsoft.AspNet.Mvc": "",
"Microsoft.AspNet.Mvc.TestConfiguration": ""
},
"frameworks": {
"net45": { },
"k10": { }
}
}

0 comments on commit 791518d

Please sign in to comment.