-1

Hi I have an interface which is implemented by multiple classes.

public interface IHuman
{
    void Talk();
}

public class AdultHuman
{
    public void Talk()
    {
          Console.Writeline("Hi");
    }
}

public class BabyHuman
{
     public void Talk()
    {
          Console.Writeline("Babble");
    }
}


public enum HumanEnums
{
    Adult,
    Baby
}

Currently in my startup add on I have

services.AddSingleton<AdultHuman>();
services.AddSingleton<BabyHuman>();

We are constantly adding different implementations of IHumans so I would like my start up add on to be dynamic to add the singletons with a forloop looping through the values of the HumanEnums so it would look like this

var enumTypes = Enum.GetValues(typeof(ActionTypes));
foreach(var enum in enumTypes)
{
     var type = typeof(IHuman);

     // namespace + name of class i.e MyProgram.Humans.BabyHuman
     var typeName = $"{type.Namespace}.{action}Human";
     var t = Type.GetType(typeName, true);
     services.AddSingleton< --something here-- >();
}

How would I achieve this?

P.S. Also it would be helpful if instead of looping through the enums, I could find all implementations of IHuman and loop through that.

MrHungrayMan
  • 231
  • 3
  • 9
  • Possible duplicate of [Getting all types that implement an interface](https://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface) – mjwills Sep 14 '17 at 21:58
  • After you have the implementing types, call `public static IServiceCollection AddSingleton( this IServiceCollection services, Type serviceType, Type implementationType)` – mjwills Sep 14 '17 at 22:00
  • That looks like you'd want a dependency injection tool to manage that scenario, e.g., Ninject or StructureMap. These tools not only handle object creation but their scope as well. – DiskJunky Sep 14 '17 at 22:45
  • @mjwills I was able to get `typeof(IHuman).GetTypeInfo().Assembly.DefinedTypes.Where(t => typeof(IHuman).GetTypeInfo().IsAssignableFrom(t.AsType()) && t.IsClass); ` And it got an `IEnumerable` How would I pass that through to the AddSingleton parameters? – MrHungrayMan Sep 15 '17 at 00:49
  • https://stackoverflow.com/questions/43523510/net-framework-get-type-from-typeinfo shows you how to map a `TypeInfo` to `Type`. So `foreach` over the `IEnumerable`, map the `TypeInfo` to `Type` and then call the `AddSingleton` method I mention earlier. – mjwills Sep 15 '17 at 00:52

1 Answers1

3

Thanks guys I was able to solve it with your help! I didnt realize that you could add single with types instead of classes. So I used AddSingleton(typeof(Adult)); instead of AddSingleton();

var humanTypes = typeof(IHuman).
            GetTypeInfo().Assembly.DefinedTypes
            .Where(t => typeof(IHuman).GetTypeInfo().IsAssignableFrom(t.AsType()) && t.IsClass)
            .Select(p => p.AsType());


foreach(var humanType in humanTypes )
{
    services.AddSingleton(humanType);
}
MrHungrayMan
  • 231
  • 3
  • 9