I am writing an application that consists of an Importer and a Processor. The Importer will take a type and instantiate a List<> of that type. The Processor needs to take that returned list.
For example, I want to call Importer<Organisation>.GetObjects() and have it return a List<Organisation>. Then pass the List to my OrganisationProcessor.
Similarly, I want to call Importer<Address>.GetObjects() and have it return a List<Address>. Then pass the List to my AddressProcessor.
I would like to put the creation of the Importer<> and *Processor into a factory. I have removed all code and produced an uncontaminated sample below. My attempts have been met with no success and may be down to topics like variance which I don’t fully understand.
class Program
{
static void Main(string[] args)
{
//What I am currently doing
Importer<Organisation> importer = new Importer<Organisation>();
List<Organisation> list = importer.GetObjects();
OrganisationProcessor processor = new OrganisationProcessor();
processor.Process(list);
//***What I want to do***
string name = "Organisation"; //Passed in from external source
var importer = Factory.GetImporter(name); //returns Importer<Organisation>
var processor = Factory.GetProcessor(name); //returns OrganisationProcessor
processor.Process(importer.GetObjects()); //.Process takes List<Organisation>
}
}
public class Importer<T>
{
public List<T> GetObjects()
{
return new List<T>();
}
}
public class OrganisationProcessor
{
public void Process(List<Organisation> objects)
{
//Do something
}
}
public class AddressProcessor
{
public void Process(List<Address> objects)
{
//Do something
}
}
public class Organisation { }
public class Address { }
This should do the trick, note that your initial intention hasn’t been changed, which is surprise even for me. Also note that you have to add namespaces to type literals in Factory. Using LINQ to find types is more flexible, but it’s much readable to enter path to type with namespace in one line. I have executed this sample on project without namespaces and it worked fine.