c# - Structuremap addalltypesof constructed by a specific constructor -


i structuremap ioc-framework convention based registration. try following: want add types implement specific interface when class has default (no parameters) constructor. , types must created using constructor.

this have untill now, registers correct types, how specify default constructor should used when creating instance.

public class myregistry : registry     {     public myregistry()     {         scan(            x =>            {                x.assemblycontainingtype<iusecase>();                x.exclude(t => !hasdefaultconstructor(t));                x.addalltypesof<iusecase>();            });     }     private static bool hasdefaultconstructor(type type)     {         var _constructors = type.getconstructors();         return _constructors.any(c => isdefaultconstructor(c));     }      private static bool isdefaultconstructor(constructorinfo constructor)     {         return !constructor.getparameters().any();     } } 

there few ways force structuremap use specific constructor. simplest put defaultconstructor attribute on constructor want use. assuming don't want that, have create custom registrationconvention.

public class usecaseregistrationconvention : iregistrationconvention {     public void process(type type, registry registry)     {         if (type.isabstract || type.isinterface || type.isenum)             return;          var usecaseinterface = type.getinterface("iusecase");         if (usecaseinterface == null)              return;          var constructor = type.getconstructors().firstordefault(c => !c.getparameters().any());         if (constructor != null)         {             registry.for(usecaseinterface).add(c => constructor.invoke(new object[0]));         }     } } 

then use in scan call:

scan(x =>    {        x.assemblycontainingtype<iusecase>();        x.with(new usecaseregistrationconvention());    }); 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -