In general reflection in a base class can be put to some good and useful ends, but I have a case here where I'm between a rock and a hard place... Use Reflection, or expose public Factory classes when they really should be private semantically speaking (ie. not just anyone should be able to use them). I suppose some code is in order here:
public abstract class SingletonForm<TThis> : Form
where TThis : SingletonForm<TThis>
{
private static TThis m_singleton;
private static object m_lock = new object();
private static ISingletonFormFactory<TThis> m_factory;
protected SingletonForm() { }
public static TThis Singleton
{
get
{
lock (m_lock)
{
if (m_factory == null)
{
foreach (Type t in typeof(TThis).GetNestedTypes(BindingFlags.NonPublic))
{
foreach (Type i in t.GetInterfaces())
{
if (i == typeof(ISingletonFormFactory<TThis>))
m_factory = (ISingletonFormFactory<TThis>)Activator.CreateInstance(t);
}
}
if (m_factory == null)
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"{0} does not implement a nested ISingletonFormFactory<{0}>.",
typeof(TThis).ToString()));
}
if (m_singleton == null || m_singleton.IsDisposed)
{
m_singleton = m_factory.GetNew();
}
return m_singleton;
}
}
}
}
Now, this code works for me, but is it a horrible kludge and/or a really bad idea? The other option is passing in the Factory's type as a type paramater, but then due to visiblity limitations, the Factory class must be public which means anyone can call it to make instances when they shouldn't be.