2008-11-10 48 views
0

我需要在ASP.NET中实现经典的Factory Method模式以动态地创建服务器控件。在ASP.NET中实现WebControl工厂

我发现创建.ascx控件的唯一方法是使用Page/UserControl类的LoadControl方法。然而,我发现将我的工厂链接到页面或将页面参数传递给工厂时很麻烦。

有没有人知道另一种方法来创建这样的控件(例如静态方法,我会忽略)?

谢谢。

回答

1

最后,我决定将页面作为参数传递给工厂。要对工厂方法容易拨打电话,我改变了工厂类从单身到公共课,我通过页面的构造器:

public ControlsFactory 
{ 
    private Page _containingPage; 

    public ControlsFactory(Page containingPage) 
    { 
     _containingPage = containingPage; 
    } 

    public CustomControlClass GetControl(string type) 
    { 
     ... snip ... 
     CustomControlClass result = (CustomControlClass)_containingPage.LoadControl(controlLocation); 

     return result; 
    } 
} 

因为我必须初始化与每个页面上的多个控件工厂,这可能是实现该模式的最简洁可用的方式。

0

打开反射器后,在页面中使用的LoadControl函数在任何TemplateControl中都可用。

实际的LoadControl内部使用BuildManager中的内部方法,所以我不认为有一种方法可以在不使用反射的情况下使用静态方法。

至少你不需要传递一个页面。子类化TemplateControl将工作。