c# - Detecting all concrete implementions of interfaces at run time -


i'm trying create code detects concrete implementations of interface within c#. dont believe problem facing confined c# , general oop question.

i want detection @ runtime have ability expand implementations of interface @ future date.

what options/approaches available me in order achieve this?

for example

public interface ianimal{  void makenoise(); } public class dog : ianimal{   public void makenoise()   {     console.writeline("woof");   } } public class cat : ianimal{   public void makenoise()   {     console.writeline("meow");   } } public class animalinstancecontroller{   /*im trying populate classes implement ianimal    */      public ienumerable<ianimal> {get;set;} } 

thanks

nicholas

you can relatively using reflection, eg:

        var assemblies = appdomain.currentdomain.getassemblies();         var alltypes = assemblies.selectmany(x => x.gettypes());         var impltypes = alltypes.where(t => !t.isinterface && !t.isabstract)                  .where(t => typeof (ianimal).isassignablefrom(t));         var animals = impltypes.select(t => (ianimal) activator.createinstance(t))                                .toarray(); 

however there number of concerns:

  1. if have dependencies in constructors, can become quite complicated resolve these
  2. how determine assemblies probe? example above probes loaded assemblies
  3. how deal constructor exceptions?

i suggest looking @ dependency injection / inversion of control container such castle windsor along automatic registration, eg:

 container.register(alltypes.fromassemblycontaining<ianimal>().basedon<ianimal>()); 

there various options of specifying assemblies scan, , if use installers, can make system quite extensible.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -