Skip to content

Instantly share code, notes, and snippets.

@damianh
Created October 12, 2017 12:49
Show Gist options
  • Save damianh/e90df88994b88f0f860074bb41ef2c47 to your computer and use it in GitHub Desktop.
Save damianh/e90df88994b88f0f860074bb41ef2c47 to your computer and use it in GitHub Desktop.
Scoping which controller types are registered in aspnet core
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