Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Adding a list of types to service builder

I am trying to take a namespace find all the classes that end with service then add them as a singleton to my service.

foreach(Type serviceClass in GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyProject.Services"))
{
    services.AddSingleton<serviceClass.GetType()>;
}

This does not compile, so any help would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...