Unfortunatley ASP.NET似乎並不支持控件的任何方便工廠創建模式。但是,在3.5中,您可以非常細緻地控制ASP.NET運行時爲.aspx文件生成的實際代碼。
只需將[ControlBuilder(...)]屬性應用於您想要由容器構建的所有控件。創建子類ControlBuilder並重寫ProcessGeneratedCode以將構造函數替換爲對容器的調用。
這裏有一個簡單的例子:
public class ServiceProviderBuilder : ControlBuilder
{
public override void ProcessGeneratedCode(System.CodeDom.CodeCompileUnit codeCompileUnit, System.CodeDom.CodeTypeDeclaration baseType, System.CodeDom.CodeTypeDeclaration derivedType, System.CodeDom.CodeMemberMethod buildMethod, System.CodeDom.CodeMemberMethod dataBindingMethod)
{
// search for the constructor
foreach (CodeStatement s in buildMethod.Statements)
{
var assign = s as CodeAssignStatement;
if (null != assign)
{
var constructor = assign.Right as CodeObjectCreateExpression;
if (null != constructor)
{
// replace with custom object creation logic
assign.Right = new CodeSnippetExpression("("+ ControlType.FullName + ")MyContainer.Resolve<" + ControlType.BaseType.FullName + ">()");
break;
}
}
}
base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod);
}
}
[ControlBuilder(typeof(ServiceProviderBuilder))]
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public WebUserControl1()
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
不幸的是,我們在這個庫中有很多用戶控件,所以它不能直接移植到MVC中。並用構造函數注入用戶控件不起作用,但我已經計算出我將相關信息/行爲注入到字段中。 – 2009-01-05 16:28:01