ASP.NET MVP Injecting Service Dependency

女生的网名这么多〃 提交于 2019-11-30 15:25:38

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.

In our homegrown MVP-framework we had a typed base-class that all Pages inherited from. The type needed to be of type Presenter (our base presenter class)

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

Sample code:

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!

I haven't seen a general purpose method for doing constructor injection on webforms. I assume it may be possible via a PageFactory implementation, but since most on the edge right now are moving to MVC rather than webforms, that may not happen.

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

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

    public IBlogDataService DataService{get;set;}
    public _Default()
    {
    }
}

I know this doesn't specifically solve your desire to use constructor injection, but this is the closest I know of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!