2

When using Unity 2.0 for dependency injection within a web application, it appears that user controls, pages, etc will all need make explicit calls to retrieve the container and "fetch" the dependencies … so using the annotations like [dependency] won't offer any value. This is likely since the location of the container (application context, http context cache, etc.) is unknown in the web configuration.

Since Unity itself provides method interception, isn't there a way to "tell" unity how to fetch the container correctly when you build your own web application? Rather than having to create base classes for page, etc.?

1 Answer 1

1

The problem is that the WebForms Pages and Controls are not set up to allow for construction by dependency injection, so Unity never gets invoked at all unless the class invokes Unity itself. I've found the best pattern in these cases is to invoke the DI framework in the constructor via a Service Locator and then use annotations to mark dependency properties. Something like this:

public MyPage()
{
    // Injector is a wrapper class so you can change the underlying DI framework
    // later if necessary.
    Injector.Inject(this); 
}

[Dependency]
public SomeService MyService {get;set;}
Sign up to request clarification or add additional context in comments.

6 Comments

couldn't an interceptor be used to do the same thing without requiring modifications of all of the controls and pages?
@BrianBeckham: No. What method would you intercept? Interceptors will only work on objects that your DI framework created in the first place. Since WebForms doesn't provide any hooks, you can't get your foot in the door in the first place.
I was hoping that something within Unity itself could be intercepted, but it looks as if it isn't the problem....what about creating something in the asp.net pipeline instead?
@BrianBeckham: If Unity never gets invoked in the first place, there's nothing to intercept. And WebForms doesn't give you the hooks you need to cause Unity to be invoked when creating a new control or page. MVC is much better about this sort of thing, since it lets you tell it what factory implementation to use when it needs to build a controller.
@BrianBeckham: That HttpModule is an interesting approach and may work in some cases. Bear in mind that it doesn't take effect until the OnPageInitComplete event, meaning that if you need to use any dependencies during the Init phase of any of your controls you're out of luck.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.