本文介绍了使用Autofac与ASP.NET和MVP模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想Autofac集成到exsisting ASP.NET Web应用程序。

I'm trying to integrate Autofac into an exsisting ASP.NET web application.

该页面遵循MVP模式。每个页面实现了查看和委托功能到presenter。查看注入presenter直通构造。

The pages follow the MVP pattern. Each page implements a View and delegate functionality to a Presenter. The View is injected into the Presenter thru the constructor.

我能够注册presenter和查看和页面加载正常,但当回传发生在视图中的用户控件是空的。看来,Autofac创建页面的新实例,给到presenter,而不是给它实例真正的Page实例。有没有一种方法能与Autofac注册页面实例?

I was able to register the Presenter and View and the page loads fine but when a postback happens the user controls on the view are null. It seems that Autofac creates a new instance of the Page to give to the presenter instead of giving it the instance real Page instance. Is there a way to have Page instances registered with Autofac?

有没有人使用Autofac与ASP.NET和MVP?

Has anyone use Autofac with ASP.NET and MVP?

谢谢!

推荐答案

有一个更好的办法。首先,启用。这将使自动物业注入的实例。

There is a better way. First, enable the Web integration module. This will enable automatic property injection into the Page instance.

由于您的presenter需要在其构造的观点,你的页面应该采取一个presenter依赖的工厂而不是presenter本身。

Since your presenter needs the view in its constructor, your page should take a dependency on a presenter factory instead of the presenter itself.

所以,首先你需要presenter工厂,这是必要的参数的委托:

So, first you need the presenter factory, which is a delegate with the necessary parameters:

public delegate IOCTestPresenter IOCTestPresenterFactory(IIOCTestView view);

这代表必须在presenter构造函数的参数(类型和名称)匹配:

This delegate must match the parameters (type and name) of the presenter constructor:

public class IOCTestPresenter
{
     public IOCTestPresenter(IIOCTestView view)
     {
     }
}

在你看来,添加属性接收工厂的委托,并使用委托创建presenter:

In your view, add a property receiving the factory delegate, and use the delegate to create the presenter:

public partial class IOCTest
{
     public IOCTestPresenterFactory PresenterFactory {get;set;}

     protected void Page_Load(object sender, EventArgs e)
     {
           var presenter = PresenterFactory(this);
     }
}

在您的容器的设置,你将不得不作出如下注册:

In your container setup you will have to make the following registrations:

builder.Register<IOCTestPresenter>().FactoryScoped();
builder.RegisterGeneratedFactory<IOCTestPresenterFactory>();

这篇关于使用Autofac与ASP.NET和MVP模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:37