.net - How can I inject run-time parameters along with a volatile dependency into a constructor with Castle Windsor? -
some of classes have constructor similar following:
public class mycomponent : basecomponent, imycomponent { public mycomponent(ipostrepository postsrepo, int postid, icollection<string> filenames) { // ... } } ipostrepository volatile dependency, can initialized @ application start. postid , filenames arguments known @ run time.
how can use castle windsor (3.2.0, if matters) handle injection of ipostrepository dependency while still allowing run-time constructor parameters?
(while 1 approach might refactor mycomponent, significant undertaking many other portions of code refer mycomponent.)
here's i've gotten far: think need create mycomponentfactory. interface of mycomponentfactory like
public interface imycomponentfactory { imycomponent create(params object[] args); } this imycomponentfactory injected layer above (the controller in case) so:
public class mycontroller : controller { private imycomponentfactory _mycomponentfactory; public mycontroller(imycomponentfactory mycomponentfactory) { _mycomponentfactory = mycomponentfactory; } public actionresult myaction(int postid) { list<string> filenames = new list<string>(); // ... // creates new instance of resolved imycomponent ipostrepository injected imycomponentfactory , run time parameters. imycomponent mycomponent = _mycomponentfactory.create(postid, filenames); // stuff mycomponent return view(); } } finally, have attempted let castle windsor create factory implementation registering imycomponentfactory in composition root so:
// add factory facility container.addfacility<typedfactoryfacility>(); container.register(component.for<imycomponentfactory>().asfactory()); doing results in dependencyresolverexception message of
could not resolve non-optional dependency 'playground.examples.components.mycomponent' (playground.examples.components.mycomponent). parameter 'postid' type 'system.int32'
the error makes sense, , i'm guessing need create custom implementation of imycomponentfactory, i'm not sure how go it.
why can't following:
public class mycomponentfactory : imycomponentfactory { private ipostrepository postrepository; public mycomponentfactory(ipostrepository postrepository) { this.postrepository = postrepository; } public imycomponent create(int postid, icollection<string> filenames) { return new mycomponent(this.postrepository, postid, filenames); } } i use explicit parameters in create method.
then register mycomponentfactory against interface imycomponentfactory (as singleton)
Comments
Post a Comment