structuremap - Restrict injection by namespace -
i have following configuration:
for<itranslatorprovider>().singleton().use<translatorprovidera>();
i have 3 translator providers: translatorprovidera, b , c.
each 1 should used under namespaces.
project.services > use provider a
project.site > user provider b
...
can inject provider a, b or c depending namespace request came?
is possible?
you should able using a convention. ought work:
using system; using system.linq; using structuremap.configuration.dsl; using structuremap.graph; using structuremap.typerules; class translationconvention : iregistrationconvention { public void process(type type, registry registry) { if(!type.isconcrete()) return; var ctor = constructor.getgreediestconstructor(type); var translatorparameters= ctor.getparameters() .where(p => typeof(itranslatorprovider) .isassignablefrom(p.parametertype)); if(!translatorparameters.any()) return; type translatortype = gettranslatortype(type); translationparameters.aggregate(registry.for(type).use(type), (current, parameter) => current.ctordependency<itranslatorprovider>(parameter.name) .isconcretetype(translatortype)); } type gettranslatortype(type type) { if(type.namespace == "project.services") return typeof(translatorprovidera); if(type.namespace == "project.site") return typeof(translatorproviderb); return typeof(translatorproviderc); } }
the convention above works registering concrete types, if want convention bind classes interface need change part: registry.for(type).use(type)
more fitting. have @ built in conventions in structuremap ideas.
you can use convention in scan:
objectfactory.initialize(c => c.scan(s => { s.thecallingassembly(); s.convention<translationconvention>(); }) );
Comments
Post a Comment