Search code examples
c#asp.netdependency-injectioninversion-of-controlmvp

ASP.NET MVP Injecting Service Dependency


I have an ASP.NET page that implements my view and creates the presenter in the page constuctor. Phil Haack's post providing was used as the starting point, and I'll just the examples from the post to illustrate the question.

public partial class _Default : System.Web.UI.Page, IPostEditView {

    PostEditController controller;
    public _Default()
    {
         this.controller = new PostEditController(this, new BlogDataService());
    }
}

What is the best approach to inject the instance of the BlogDataService? The examples I have found use properties in the Page class for the dependency marked with an attribute which the injection framework resolves.

However, I prefer using the constructor approach for testing purposes.

Does anyone have input or perhaps links to good implementations of the above. I would prefer Ninject, but StructureMap or Windsor would be fine as long as its fluent.

Thanks for any feedback.


Solution

  • If you use the Microsoft ServiceLocator, you can apply the service locator design pattern and ask the container for the service.

    In your case it would look something like this:

    public partial class _Default : System.Web.UI.Page, IPostEditView {
    
        PostEditController controller;
        public _Default()
        {
             var service = ServiceLocator.Current.GetInstance<IBlogDataService>();
             this.controller = new PostEditController(this, service);
        }
    }
    

    ServiceLocator has implementations for Castle Windsor and StructureMap. Not sure about Ninject, but it's trivial to create a ServiceLocator adapter for a new IoC.