views:

73

answers:

3

Does Castle Windsor support applying setter injection to existing service instances? I have a case in which I have no control over the creation of certain class instances while I do need to resolve dependencies for them. This rules out constructor injection but leaves the door open for setter injection since I can intercept the new instances right after they're created.

I know Castle Windsor supports setter injection out of the box, I just don't know whether its possible (and if so: how) to leverage it explicitly without using the Resolve method.

I know as well that such thing is possible in StructureMap, using the ObjectFactory.BuildUp method so that raises my hope of finding an equivalent in Castle Windsor.

In case you are wondering, I'm applying dependency injection to pages in ASP.NET WebForms, providing a custom PageHandlerFactory. I don't want to go down the path of trying to create the page handler myself, I should leave that to the base implementation in the PageHandlerFactory class.

public class CustomPageHandlerFactory : PageHandlerFactory
{
    public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
    {
        IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path);
        Page page = handler as Page;

        if (page == null)
        {
            return handler;
        }

        // Resolve dependencies using setter injection...

        return page;
    }
}
+1  A: 

See the bottom of this article:

http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/

Jeremy provides an extension method for the Windsor Container that implements property injection.

Patrick Steele
Thanks. The provided code implements the injection instead of leaving it up to Windsor and is not very performant due to the reflection code and the absence of a caching mechanism. I'll stick it into my code base as a temporary solution though, until I have a more elegant solution.
Sandor Drieënhuizen
+1  A: 

Does Castle Windsor support applying setter injection to existing service instances?

No. Check out the FAQ for rationale.

I'm applying dependency injection to pages in ASP.NET WebForms,

See this question.

Mauricio Scheffer
I see. I'm thinking of writing a facility that uses a lazy component loader to do the setter injection. I know it's all a bit smelly but I think that's inevitable when using ASP.NET WebForms.
Sandor Drieënhuizen
+1  A: 

Check out Neal Shawn's ASpNetWindsorModule.

roelofb
Thanks, that module is really neat!
Sandor Drieënhuizen
I just wish it supported setter injection for user controls.
Sandor Drieënhuizen
It does support that. Only when you use LoadControl() yourself it will not work OOTB.
roelofb
That's indeed what I am using. Wrapping `LoadControl` quickly solves that though.
Sandor Drieënhuizen