Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...