Reflecting Factory Interfaces across Assemblies

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

This is a technically challenging question but it would help me significantly
if anyone can answer it.

In essence I have the following:

A factory class, which can create producer classes which inherit an
interface (standard factory design pattern).

I would like to make this more versatile and do the following:

I would like to be able to specify the producer classes in a config file and
then call them at runtime. This would allow me to create the producer class
in a separate assembly and then use reflection to call the functions.

Does anyone have a Factory class which could do this?

The bit I am finding most difficult is the reflection. So any help on this
would be appreciated.

Mark
 
I would like to be able to specify the producer classes in a config file and
then call them at runtime. This would allow me to create the producer class
in a separate assembly and then use reflection to call the functions.

In your config:

<add key="FactoryInstance" value="SomeNameSpace.SomeType,
SomeNameSpace.dll" />

Your factory interface:

public interface IMyFactoryInterface {
IProducer CreateInstance();
}


Your instance - in the assembly SomeNameSpace.dll:

public class Factory : IMyFactoryInterface {
public IProducer CreateInstence() {
return new Producer();
}
}


Get the factory:

[..]
IMyFactoryInterface currentFactroy = null;
string[] factorySettings =
System.Configuration.ConfigurationSettings.AppSettings["FactoryInstance"].ToString().Split(',');
string type = factorySettings[0].Trim();
string assembly = factorySettings[1].Trim();
currentFactory = Assembly.Load(assembly).CreateInstance(type) as
IMyFactoryInterface;

//Get the producer instance
if (currentFactory != null) {
IProducer producer = currentFactory.CreateInstance();
}
[..]

You'll need to add exception handling your self.

/B.factoring
 
Ups.. I misread your question - it wasn't the factory class you wanted
to be configurable.. (Yeah - I know I should read twice <hrmpf.wav>)

Anyway - it's almost the same principle. But why would you call the
methods via reflection?

Anyway - in your factory, just do the same, as we did in the previous
post, when getting the Factory.

public class Factory {
public object CreateProducer() {
//get the configured procucer class / assembly
//load the assembly
return
MyAssembly.CreateInstance(configuredProducerName);
}
}
 
Back
Top