Is there a good example for naive assembly initialization?

Let's say we have several assemblies, and they all implement IAnimal, and we would like to go to one place to find out if there is another IAnimal implementation.

features:

  • we do not need prior knowledge outside the assembly

  • the assembly may have a register class / method

  • it is preferable not to use reflection. So far this seems to be the only way though

discussion:

It seemed to me that I am doing this statically through inheritance, however I do not know about the assembly level initialization sequence.

+4
source share
3 answers

When starting the application, you can register in the AssemblyLoad of your AppDomain:

AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(NewAssemblyLoaded); 

and define NewAssemblyLoad to add IAnimal implementations to the list of types (e.g. animalTypes) that you support:

 static void NewAssemblyLoaded(object sender, AssemblyLoadEventArgs args) { Assembly anAss = args.LoadedAssembly; foreach (Type t in Assembly.GetTypes()) { if (!t.IsInterface && typeof(IAnimal).IsAssignableFrom(t)) animalsList.Add(t); } } 
+1
source

I suggest a look at MEF . It is practically designed for this kind of thing.

It uses reflection because it is a mechanism created for such dynamic detection. I doubt that you will find a solution that does not use any level of reflection.

+6
source

I wrote an extension method that allows you to search for expanded types that match certain criteria at runtime - it uses Reflection, but you may find it useful.

 IEnumerable<Type> animalTypes = Assembly.GetExecutingAssembly() .GetAvailableTypes( typeFilter: t => !t.IsInterface && typeof(IAnimal).IsAssignableFrom(t)); 
+1
source

All Articles