Like this. Modify the Type.GetType line if the implementation and stub isnt in the same assembly or namespace.
class UberCoolFactory
{
public static T CreateStubs<T>()
{
string ns = typeof(T).Namespace;
string name = typeof(T).Name;
string assembly = typeof(T).Assembly.GetName().Name;
Type type = Type.GetType(string.Format("{0}.{1}Stub, {2}", ns, name, assembly));
return (T)Activator.CreateInstance(type);
}
}
Alternative:
class FactoryTwo
{
/// <summary>
/// Search through all loaded assemblies that exists in the current directory.
/// </summary>
/// <typeparam name="T"></typeparam>
public static T CreateStub<T>() where T : class
{
string currentDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string wantedTypeName = typeof(T).Name + "Stub";
List<Type> foundTypes = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (!currentDir.Equals(Path.GetDirectoryName(assembly.Location)))
continue;
foreach (var type in assembly.GetTypes())
{
if (!type.Name.Equals(wantedTypeName))
continue;
foundTypes.Add(type);
}
}
if (!foundTypes.Any())
return null;
if (foundTypes.Count > 2)
throw new AmbiguousMatchException("Found multiple stubs implementing '" + typeof(T).FullName + "'.");
return (T) Activator.CreateInstance(foundTypes[0]);
}
}
Usage:
var instance = UberCoolFactory.CreateStubs<Foo>();
var instance2 = FactoryTwo.CreateStub<Foo>();