Asp.net MVP & MVC 之 ASP.NET Model-View-Presenter

The Unity IoC Container can be used in your ASP.NET Web Applications to provide dependency injection, especially when using Model-View-Presenter. There are several ways that one can use Unity to wire-up the presenter class and its dependencies to the ASP.NET view. In this example, I will use a Page Base Class that accesses the UnityContainer on the HttpApplication Class and uses Unity to create an instance of the Presenter Class associated with the view.

First Thoughts - ASP.NET MVC and MVCContrib

Before I jump into this tutorial I would like to mention a similar tutorial on using Unity with the ASP.NET MVC Framework. The reason being that I modeled this tutorial after the ASP.NET MVC and Unity Tutorials:

The technique of adding the UnityContainer via IUnityContainer on the HttpApplication Class was taken from the WindsorControllerFactory in MVCContrib.

Creating and Initializing Unity IoC on HttpApplication Class in Global.asax

We need a way to access the Unity Dependency Injection Container from our websites. Normally I use a ServiceLocator Class, but for this example I thought I would add the Unity Container to the HttpApplication Class as a static variable.

Here is some sample code for adding an initializing the UnityContainer on the HttpApplication Class:

public class Global : HttpApplication, IContainerAccessor
{
    private static IUnityContainer _container;

    public static IUnityContainer Container
    {
        get { return _container; }
    }

    IUnityContainer IContainerAccessor.Container
    {
        get { return Container; }
    }

    protected void Application_Start(object sender, EventArgs e)
    {
        InitializeContainer();
    }

    private static void InitializeContainer()
    {
        if (_container == null)
            _container = new UnityContainer();

        _container
            .RegisterType<IBlogDataSource, BlogDataSource>
(new ContainerControlledLifetimeManager()) .RegisterType<ILogger, NullLogger>()
(new ContainerControlledLifetimeManager())
} }

I have registered a couple of type mappings with Unity. Unity will return BlogDataSource when I request IBlogDataSource and NullLogger when I request ILogger. Both are registered as singletons and I took advantage of the Unity Fluent Interface to register the services. I could have registered these services in a configuration file as well.

In addition, I created a separate interface, called IContainerAccessor that defines access to the IUnityContainer:

public interface IContainerAccessor
{
    IUnityContainer Container { get; }
}

I rather like the interface as it formalizes the process of getting the Unity Container from the HttpApplication Class as we will see in a moment.

Unity IoC and Model-View-Presenter

I have a ASP.NET Page in my web application, called AddBlog that uses Model-View-Presenter to add a blog to my ASP.NET website. The code for my view is as follows:

public partial class AddBlog :
        ViewPage<IAddBlogView,AddBlogPresenter>, IAddBlogView
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            Presenter.OnViewInitialized();
        }
        
        Presenter.OnViewLoaded();
    }

    public string BlogTitle
    {
        get { return txtBlogTitle.Text; }
    }

    protected void btnAddBlog_Click(object sender, EventArgs e)
    {
        Presenter.OnAddBlog();
    }
}

The page receives the Click Event of the AddBlog Button and passes the request to the Presenter. In this case I am delegating requests to the presenter. I could have just as easily had the Presenter Class subscribe to various View Events. To each his own.

The ASP.NET Page ( View ) derives from a ViewPage Base Class, which is doing all the work to inject the Presenter into the View using Unity:

abstract public class ViewPage<TView,TPresenter>
    : Page where TPresenter : Presenter<TView> where TView : class
{
    public TPresenter Presenter { get; set; }

    protected void Page_Init(object sender, EventArgs e)
    {
        IContainerAccessor accessor =
            Context.ApplicationInstance as IContainerAccessor;
if (accessor == null || accessor.Container == null)
throw new InvalidOperationException("Cannot Find UnityContainer");
Presenter = container.Resolve<TPresenter>(); Presenter.View = this as TView; } }

We first access the IUnityContainer from the HttpApplication Class and then have the Unity Container create the appropriate Presenter Class and add the view to it.

The Presenter<TView> Class is as follows:

abstract public class Presenter<TView>
{
    public TView View { get; set; }

    virtual public void OnViewInitialized()
    {
    }

    virtual public void OnViewLoaded()
    {
    }
}

and my AddBlogPresenter Class is as follows:

public class AddBlogPresenter : Presenter<IAddBlogView>
{
    private readonly IBlogDataSource _blogDataSource;

    public AddBlogPresenter(IBlogDataSource blogDataSource)
    {
        _blogDataSource = blogDataSource;
    }

    public void OnAddBlog()
    {
        Blog blog = new Blog { Title = View.BlogTitle };
        _blogDataSource.AddBlog(blog);
        // ...
    }
}

All of this means that Unity will create my AddBlogPresenter Class and in turn inject the BlogDataSource Service into it. The BlogDataSource has a dependency on ILogger and Unity will inject NullLogger into BlogDataSource:

public class BlogDataSource : IBlogDataSource
{
    private readonly ILogger _logger;

    public BlogDataSource(ILogger logger)
    {
        _logger = logger;
    }

    public void AddBlog(Blog blog)
    {
        _logger.Log(blog.Title);
    }
}

I didn't appropriately check for null arguments, etc. to keep the code easy-to-read. Make sure you do that in your production applications.

Conclusion

This tutorial on Unity shows one way of using it for IoC and dependency injection needs in your ASP.NET Web Applications. There are other ways to achieve this as well. This tutorial is based on the Unity February 2008 CTP.

I hope it helps.

David Hayden

Tags: DependencyInjection, IoC, ModelViewPresenter, Unity

原文:http://www.pnpguidance.net/Post/UnityIoCDependencyInjectionASPNETModelViewPresenter.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MVCModel-View-Controller)架构是一种软件设计模式,用于将应用程序的逻辑分离为三个不同的组件:模型(Model)、视图(View)和控制器(Controller)。每个组件都有自己的职责和功能。 1. 模型(Model): 模型代表应用程序的数据和业务逻辑。它负责处理数据的获取、存储、更新和验证。模型通常包括数据结构、数据库操作、网络请求等。模型不依赖于视图或控制器,它独立于用户界面。 2. 视图(View): 视图是用户界面的可视化部分,负责展示数据给用户,并接收用户的输入。它可以是一个界面、一个页面或一个控件。视图从模型中获取数据,并将其呈现给用户。视图不负责处理数据的获取或处理逻辑,它只负责展示和接收用户操作。 3. 控制器(Controller): 控制器是模型和视图之间的桥梁,负责协调用户界面和应用程序的交互。它接收用户的输入,并根据输入更新模型或视图。控制器可以处理用户事件、调用模型的方法、更新视图等操作。控制器还可以根据需要调整模型和视图之间的通信。 MVC架构的优势在于它实现了逻辑的分离,使得代码更易于维护、测试和扩展。模型和视图之间的解耦使得可以独立修改其中一个组件,而不会影响其他组件。控制器作为中介者处理用户交互,并协调模型和视图的更新。这种分离提高了代码的可读性、可维护性和可重用性。 在Android开发中,MVC架构通常被扩展为MVPModel-View-Presenter)或MVVM(Model-View-ViewModel)模式,以适应Android框架的特点和要求。这些扩展模式在MVC的基础上进一步优化了代码结构和组件之间的交互方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值