c# - Webforms and Dependency Injection -


i in process of introducing dependency injection framework existing webforms application (using castle windsor).

i have pretty deep experience di, , tend favor constructor injection on setter injection. if familiar webforms, know asp.net framework handles construction of page , control objects, making true constructor injection impossible.

my current solution register container in application_start event of global.asax, , keep container public static variable in global well. resolve each service need directly in page or control when need them. @ top of each page, end code this:

private readonly imyservice _exposuremanager = global.ioc.resolve<imyservice>(); private readonly imyotherservice _tencustomersexposuremanager = global.ioc.resolve<imyotherservice>(); 

obviously, don't having these references container scattered application or having page/control dependencies non-explicit, have not been able find better way.

is there more elegant solution using di webforms?

i agree @darindimitrov mvp interesting option. however, when working legacy application, rewriting existing page mvp pattern hell of job. in case might better start service locator pattern (but only in ui classes) doing. however, change 1 thing. not expose chosen di container application, expect doing global.ioc property.

instead, create static resolve<t> method on global class. hides container , allows swap implementations without having change in web pages. when this, there no advantage in using common service locator @wiktor proposes. common service locator abstraction doesn't have abstracted (since you've abstracted away container using global.resolve<t>).

unfortunately web forms, there not way this. simple injector, wrote integration guide web forms describes use of global.resolve<t> method, shows way tests if page classes can created. guide can used other di containers well.

btw, please keep in mind castle windsor, request must released explicitly (the register resolve release pattern). bit nasty (imo) , differs how other containers work , can source of memory leaks when not correctly.

last note. it possible constructor injection web forms. well... sort of, since call overloaded constructor using reflection after form has been created using default constructor, causes temporal coupling.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -