Files
mixtape/zero.Web/ApiControllerFeatureProvider.cs
T

50 lines
1.4 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Controllers;
using System;
using System.Collections.Generic;
2020-05-22 21:19:49 +02:00
using System.Linq;
using System.Reflection;
2020-05-22 21:19:49 +02:00
using zero.Core;
using zero.Web.Filters;
namespace zero.Web
{
public class ApiControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature>
{
2020-05-22 21:19:49 +02:00
public ApiControllerFeatureProvider()
{
}
public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
{
2020-05-26 16:04:11 +02:00
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
2020-05-26 16:04:11 +02:00
IEnumerable<Type> candidates = assemblies
.Where(assembly => !assembly.IsDynamic)
.SelectMany(assembly => assembly.GetExportedTypes().Where(x => x.GetCustomAttributes<BackofficeGenericControllerAttribute>().Any() && x.ContainsGenericParameters));
2020-05-22 21:19:49 +02:00
foreach (Type candidate in candidates)
{
Type genericType = candidate.GetGenericTypeDefinition();
Type[] arguments = genericType.GetGenericArguments();
Type desiredInterface = arguments.FirstOrDefault()?.GetInterfaces().FirstOrDefault();
2020-05-22 21:19:49 +02:00
if (desiredInterface == null)
{
continue;
}
2020-05-22 21:19:49 +02:00
Type implementation = EntityMap.Get(desiredInterface);
if (implementation != null)
{
TypeInfo type = candidate.MakeGenericType(implementation).GetTypeInfo();
feature.Controllers.Add(type);
}
2020-05-22 21:19:49 +02:00
}
}
}
}