dependency injection - How to resolve a type by name from the container at runtime using Autofac? -
i trying figure out how resolve type name container @ runtime using autofac 3.5.2. utilize case each business partner has custom callback strategy require injection of different types container, don't know partner strategy need until runtime. so:
class partnerastrategy(isometype asometype, ilog somelog) : icallbackstrategy {}
and
class partnerbstrategy(isomeothertype asomethingelse, ishoe asneaker) : icallbackstrategy {}
i know strategy need after class utilize has been resolved
class partnerssocontroller { void partnerssocontroller(ipartnerfactory afactory){ thepartnerfactory = afactory; } void dologin(){ // 'partnerb' string apartner = getpartnernamefromcontext(); //get container, not reflection icallbackstratgey astrategy = thepartnerfactory.resolvecallback(apartner); astratgey.execute(); } } class partnerfactory : ipartnerfactory{ icallbackstratgey resolvecallback(string apartnername){ string acallbacktypeineed = string.format("sso.strategies.{0}strategy", apartnername); // need container resolve here } }
assuming has been registered container, how register callback in autofac sso module? i've tried this:
abuilder.register(acomponentcontext => { ipartnerfactory afactory = acomponentcontext.resolve<ipartnerfactory>(); string atypename = string.format("sso.strategies.{0}strategy", /** how access partner name here? **/); type atypetoreturn = type.gettype(atypename, false, true) ?? typeof(defaultcallbackstrategy); homecoming acomponentcontext.resolve(atypetoreturn); }) .as<icallbackstrategy>()
but can see, can't figure out how create partner or type name available during callback. prefer avoid registering each partner's callback , providing key name, if possible, scan assembly types in module:
abuilder.registerassemblytypes(typeof(callbackbase).assembly) .where(atype => typeof(icallbackstrategy).isassignablefrom(atype)) .asimplementedinterfaces() .asself();
i think you're looking autofac metadata support, attribute metadata can utilize assembly scanning. plenty of docs , examples here: http://autofac.readthedocs.org/en/latest/advanced/metadata.html
dependency-injection autofac
No comments:
Post a Comment