1

I have a class named module in Modules class library.

public class Module{}

And implementations like this.

public class ModuleA: Module{...}
public class ModuleB: Module{...}
public class ModuleC: Module{...}

I want to create a class that will create instances and give me a list that inherited from Module class.

public class ModulesFactory{
  public IList<Module> GetModules(){
   ???????
   ???????
  }
}

I could not select inherited calsses in class library.

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • List inherited from Module, or List of Module inheritants? – EngineerSpock Mar 10 '15 at 07:00
  • You need to scan the assemblies where you expect the module class would be inherited. – Sriram Sakthivel Mar 10 '15 at 07:00
  • You can get the types inherited Module by using IsAssignableFrom, see this post, http://stackoverflow.com/questions/2362580/discovering-derived-types-using-reflection – Adil Mar 10 '15 at 07:08
  • **Possible duplicate** [http://stackoverflow.com/questions/2362580/discovering-derived-types-using-reflection][1] [1]: http://stackoverflow.com/questions/2362580/discovering-derived-types-using-reflection – Gaurav Sharma Mar 10 '15 at 07:10
  • I think the generic type of IList would refer to the Module in the reflection namespace... I'd put the baseclass of the Module in a Project which is referenced by both the assembly containing the factory and the modules library... then you have the basetype and can return a IList without problems (I'd rename it so it does not get mixxed up with the reflection namespace). – Florian Schmidinger Mar 10 '15 at 07:18

2 Answers2

1

Yo can create a generic method like this:

    public static IEnumerable<TModule> GetModules<TModule>()
    {
        var moduleType = typeof (TModule);

        var dependencyModuleTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(moduleType)).Select(p=>(TModule)Activator.CreateInstance(p));

        return dependencyModuleTypes;
    }

if Assembly selection is current assembly?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

it is not clear to me if you have a static list or only know the names of you classes. Why can't you just use new ModuleA() and add it to as List that you return?

If you only know the names you could use the Activator.CreateInstance method.

If both suggestions don't work, you will have to explain your problem in more detail, please.

Sascha

Sascha
  • 1,210
  • 1
  • 17
  • 33