The best approach that I found is based on this.
Would required some mother methods and classes:
You need to call this inside you Configure
:
services.RegisterAssemblyPublicNonGenericClasses()
.Where(c => c.Namespace == "")
.AsPublicImplementedInterfaces();
Create this class:
public class AutoRegisteredResult
{
internal AutoRegisteredResult(Type classType, Type interfaceType)
{
Class = classType;
Interface = interfaceType;
}
public Type Class { get; }
public Type Interface { get; }
}
And these methods:
public static IEnumerable<Type> RegisterAssemblyPublicNonGenericClasses(this IServiceCollection services,
params Assembly[] assemblies)
{
if (assemblies.Length == 0)
assemblies = new[] { Assembly.GetCallingAssembly() };
var allPublicTypes = assemblies.SelectMany(x => x.GetExportedTypes()
.Where(y => y.IsClass && !y.IsAbstract && !y.IsGenericType && !y.IsNested));
return allPublicTypes;
}
public static IList<AutoRegisteredResult> AsPublicImplementedInterfaces(this IEnumerable<Type> autoRegData)
{
var result = new List<AutoRegisteredResult>();
foreach (var classType in autoRegData)
{
var interfaces = classType.GetTypeInfo().ImplementedInterfaces;
foreach (var infc in interfaces)
{
result.Add(new AutoRegisteredResult(classType, infc));
}
}
return result;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…