Files
laatzen/LaaProductionWeb/LaaProductionWeb/App_Infrastructure/ControllersExtensions.cs
T
2023-04-28 10:40:04 +02:00

72 lines
2.5 KiB
C#

namespace LaaProductionWeb.App_Infrastructure
{
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web.Mvc;
/// <summary>
/// Static class with extension methods that run on controller contexts.
/// </summary>
public static class ControllersExtensions
{
/// <summary>
/// Adds controllers of type <see cref="IController"/> loaded by reflection from the current assembly to the <see cref="IServiceCollection"/>.
/// On this way all required services are loaded into the controller constructors.
/// </summary>
/// <param name="services"><see cref="IServiceCollection"/> provided from the extension method.</param>
/// <returns>The same <see cref="IServiceCollection"/> with added services.</returns>
public static IServiceCollection AddControllers(this IServiceCollection services)
{
var controllersMap = typeof(ControllersExtensions)
.Assembly
.GetTypes()
.Where(x => !x.IsAbstract && typeof(IController).IsAssignableFrom(x))
.Select(x => new
{
x.Name,
Path = x.FullName
.Replace("LaaProductionWeb.Controllers.", string.Empty)
.Replace(x.Name, string.Empty)
})
.GroupBy(x => x.Path)
.ToList();
var controllers = typeof(ControllersExtensions)
.Assembly
.GetTypes()
.Where(x => !x.IsAbstract && typeof(IController).IsAssignableFrom(x));
foreach (var controller in controllers)
{
services.AddTransient(controller);
}
return services;
}
public static IServiceProvider BuildControllerFactory(this IServiceProvider serviceProvider)
{
var controllerFactory = new ControllerFactory(serviceProvider);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
return serviceProvider;
}
public static string ClaimName(this IPrincipal principal)
{
if (principal is ClaimsPrincipal claimsPrincipal)
{
return claimsPrincipal
.FindAll(ClaimTypes.Name)
.LastOrDefault()?.Value;
}
return "<unknown>";
}
}
}