I’m attempting to make a generic routine within my program that will instantiate objects for me. The routines actually responsible for calling new Object() are located within a different assembly in a factory that must be instantiated.
namespace ExternalLib
{
class Object1Factory
{
public Object1 getObject1()
//...
}
class Object2Factory
// Same implementation as Object1Factory
}
I am attempting to provide a routine with my application that will allow me to call the appropriate routine to “new up” the object for me.
namespace MyApp
{
class Program
{
static void Main()
//...
static Object getNewObject(string typeName)
{
//This is where I have problems
}
}
}
I have access to the source code of both the external library as well as my program, although an entire re-write of the architecture is too costly.
What I’ve tried:
My initial idea was to use custom attributes on the factory and/or factory routine and use reflection to grab the method, then call the method. I was originally using the signature private static T getNew<T>() and attempting to use a switch statement on the type parameter, but realised getNewObject(string typeName) would be easier. Factories have the same constructor signatures, but have no inheritance link.
In summation: Routine to create objects is in factory in another assembly, how do I automatically call those routines to get objects based on type?
If you want to continue down this path – can you put all of the factory methods in a single factory class called something like ‘ObjectFactory’?
EDIT – response to James’s comment on question stating he’d prefer to keep factory classes separate:
(Using Martin’s idea below and relies on all Factory classes being names “[Type]Factory”)
(Also has non-static methods on factory class)