views:

84

answers:

3

I'm loading custom user controls into my form using reflection. I would like all my user controls to have a "Start" and "End" method so they should all be like:

public interface IStartEnd
{
    void Start();
    void End();
}

public class AnotherControl : UserControl, IStartEnd
{            
    public void Start()
    { }

    public void End()
    { }
}

I would like an interface to load through reflection, but the following obviously wont work as an interface cannot inherit a class:

public interface IMyUserControls : UserControl, IInit, IDispose
{

}
A: 

You can enforce the constraint at runtime that the class implementing IMyUserControls : IInit, IDispose also is UserControl. It's reasonable to assume that the developers providing custom controls for your app know the requirements for the controls, so I don't see a problem with performing the check at runtime.

Dan Bryant
+1  A: 

I don't see the use case, loading user controls through reflection requires knowing the type name of the control. Either use Assembly.CreateInstance if you've dynamically loaded the assembly yourself, or use the full type name with Activator.CreateInstance so that the CLR can determine what assembly needs to be loaded.

If you want to avoid specifying the user control type name then you could iterate the loaded assembly with Assembly.GetTypes() and look for a type that implements your interface. This is only going to work well if you somehow can guarantee that the assembly contains only one control.

Hans Passant
Why do you think that the assembly should have only 1 User Control?
Burt
Because you'd otherwise find more than one control that implements the interface. Which would you choose?
Hans Passant
Have a look at my answer below:http://stackoverflow.com/questions/2857448/define-interface-for-loading-custom-usercontrols-through-reflection/2859106#2859106
Burt
A: 

It sounds like what you are trying to do is very similar to the approach taken by Prism (and the Composite Application Block). Have a read at the following articles to give you an idea of what is involved:

There are loads of examples out there and this pattern is very widely used.

I hope this helps.

B

Burt