c# - LightInject IoC container resolve type by a custom method? -
is possible in lightinject ioc resolve type based on custom method?
eg resolver call method this
public interface imytype {} public class myeventype : imytype {} public class myoddtype : imytype {} public static int foo; public static imytype resolvetype() { if (foo % 2 == 0) return myeventype; return myoddtype; } how write container.register method calls above method in order resolve dependency?
lightinject allows register specific methods factory resolver methods allow construct type when resolve interface.
public class mytyperesolver { public static int foo; public static imytype resolvetype() { if (foo % 2 == 0) return new myeventype(); return new myoddtype(); } } when registering interface, instead of registering concrete type, register factory method returns concrete type.
void main() { var container = new lightinject.servicecontainer(); container.register<imytype>(factory => mytyperesolver.resolvetype()); var instance1 = container.getinstance<imytype>(); instance1.dump(); mytyperesolver.foo = 1; var instance2 = container.getinstance<imytype>(); instance2.dump(); } instance1 has concrete type of myeventype , instance2 has concrete type of myoddtype.
Comments
Post a Comment