Dependency on ASP.NET MVP Deployment

I have an ASP.NET page that implements my view and creates a presenter on a constuctor page. As a starting point, I used a post provided by Phil Haack , and I will just give examples from this post to illustrate the issue.

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 an instance of BlogDataService? The examples I found use the properties of the Page class for dependencies marked with an attribute that the injection infrastructure allows.

However, I prefer to use the constructor approach for testing purposes.

Does anyone have an input, or possibly links to good implementations above. I would prefer Ninject, but StructureMap or Windsor would be nice as long as it is fluent.

Thanks for any feedback.

+4
source share
3 answers

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

In your case, it will 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 the new IoC.

+1
source

In our home MVP structure, we had a typical base class that inherited all the pages. The type must be of type Presenter (our base presenter class)

In the base class, we then initialized the controller using the IoC container.

Code example:

 public class EditPage : BasePage<EditController> { } public class EditController : Presenter { public EditController(IService service) { } } public class BasePage<T> : Page where T: Presenter { T Presenter { get; set; } public BasePage() { Presenter = ObjectFactory.GetInstance<T>(); //StructureMap } } 

Hope this helps!

+2
source

I have not seen a general-purpose method for injecting a constructor on web forms. I suppose this is possible using the PageFactory implementation, but since most on the edge are moving to MVC right now and not to web forms, this may not happen.

However, autofac (the DI container I like a lot) has an integration module for ASP.NET WebForms that introduces a property without attributes - your code will look like this:

 public partial class _Default : System.Web.UI.Page, IPostEditView { public IBlogDataService DataService{get;set;} public _Default() { } } 

I know that this does not specifically solve your desire to use constructor injection, but this is the closest I know about.

+1
source

All Articles