views:

346

answers:

2

Hi,

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

The only way I've found to create .ascx controls is to use the LoadControl method of the Page/UserControl classes. I find it messy however to link my factory with a page or to pass a page parameter to the factory.

Does anybody know of another method to create such controls (such as a static method somewhere i'd have overlooked) ?

Thanks.

A: 

Well after opening up reflector, the LoadControl function that is being used in Page is available in any TemplateControl.

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

Well at least you don't need to pass a page around. Subclassing TemplateControl would work.

Min
+1  A: 

In the end, I decided to pass the page as a parameter to the factory. To make calls to the factory method easier, I changed the factory class from a singleton to a common 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 with the factory, this is probably the most concise and usable way to implement the pattern.

Mathieu Garstecki