Implementing WebControl Factory in ASP.NET

I need to implement the classic Factory Method pattern in ASP.NET to dynamically create server controls.

The only thing I have found to create .ascx controls is to use the LoadControl method of the Page / UserControl classes. I find it useless to link my Factory to a page or pass a page parameter to a factory.

Does anyone know of another method for creating controls like this (like a static method that I would have missed)?

Thank.

0


source to share


2 answers


In the end, I decided to pass the page as a factory parameter. To make calling the factory method easier, I changed the factory class to a singleton to a generic class, and I passed the page to the constructor:

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;
    }
}

      



Since I have to instantiate many controls on each page using a factory, this is probably the most concise and convenient way to implement the pattern.

+1


source


After opening the reflector, the LoadControl function that is used on the page is available in any TemplateControl.

Inside the actual LoadControl there are internal methods in the BuildManager, so I don't think there is a way to use static methods without using reflection.



Well, at least you don't have to go around the page. Subclassing TemplateControl will work.

0


source







All Articles