mvvm light - SimpleIoc (mvvmlight) - how to automatically register all classes implementing a particular interface -



mvvm light - SimpleIoc (mvvmlight) - how to automatically register all classes implementing a particular interface -

using simpleioc want automatically register classes implement particular interface. couldn't see method on simpleioc's container automatically set code iterate through types registered. unfortunately code's not happy (see commented line).

var types = appdomain.currentdomain.getassemblies() .selectmany(s => s.gettypes()) .where(typeof(ifoo).isassignablefrom); foreach (var type in types.where(x=>x.isclass)) { container.register<ifoo, type>(); //this line won't compile type can't resolved compiler }

i realise there less elegant ways of registering classes (such hard coding "container.register" register each class interface) i'd able add together new implementations without having maintain updating ioc installer code. useful, @ point, me able register classes in other assemblies using same method.

any thought have alter create build (or there simpler/more elegant way this)?

update fex posted comment:

"you can iterate on types (like in question) , create reflection (in mill class) - (ifoo)activator.createinstance(type); - in fact that's how service locators / ioc containers internally (in simplify)."

i've updated code next works, 1 caveat (the implementations must have parameterless constructor, , dependencies must hence satisfied mill i'm using serve instances implementing ifoo). i've included mill registration info.

updated code:

// types implement ifoo... var types = appdomain.currentdomain.getassemblies() .selectmany(s => s.gettypes()) .where(typeof(ifoo).isassignablefrom); // register these types , utilize reflection instantiate each instance... foreach (var type in types.where(x=>x.isclass)) { var t = type; container.register(() => (ifoo)activator.createinstance(t), t.tostring()); } // inject registered instances of ifoo ifoofactory when it's instantiated. // note instances of ifoo must have own dependencies satisfied via // mill @ runtime before beingness served factory. container.register<ifoofactory>( () => new foofactory(container.getallinstances<ifoo>()));

mvvm-light

Comments

Popular posts from this blog

c - Compilation of a code: unkown type name string -

java - Bypassing "final local variable defined in an enclosing type" -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -