Created
October 12, 2017 12:49
-
-
Save damianh/e90df88994b88f0f860074bb41ef2c47 to your computer and use it in GitHub Desktop.
Scoping which controller types are registered in aspnet core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using Microsoft.AspNetCore.Mvc.ApplicationParts; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace MyApp | |
{ | |
public static class MvcExtensions | |
{ | |
public static void UseControllersWithinTypeNamespace( | |
this ApplicationPartManager partManager, | |
Type type) | |
{ | |
partManager.ApplicationParts.Clear(); | |
partManager.ApplicationParts.Add(new NamespaceApplicationPart(type)); | |
} | |
public static void UseControllersWithinTypeNamespace( | |
this IMvcCoreBuilder mvcCoreBuilder, | |
Type type) | |
{ | |
mvcCoreBuilder | |
.ConfigureApplicationPartManager(partManager => partManager.UseControllersWithinTypeNamespace(type)); | |
} | |
private class NamespaceApplicationPart : ApplicationPart, IApplicationPartTypeProvider | |
{ | |
public NamespaceApplicationPart(Type namespaceType) | |
{ | |
Name = namespaceType.Namespace; | |
Types = namespaceType | |
.Assembly | |
.DefinedTypes | |
.Where(t => t.Namespace != null && t.Namespace.StartsWith(namespaceType.Namespace)) | |
.ToArray(); | |
} | |
public override string Name { get; } | |
public IEnumerable<TypeInfo> Types { get; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment