views:

244

answers:

4

(This question specifically in C#, but applies generally to .NET)

I have a largish application that has a fairly good design, and is broken into major sections over interfaces (this was done to assist parallel development).

We now have a primary set of concrete classes that implement the required interfaces, but we also have additional sets of concrete classes for alternative situations and testing.

At the moment we pull all these classes together at the top level in code:

IMyInterface xComponent = new ConcreteXComponent1();

If I want to swap out components then I only have to change that line and recompile:

// IMyInterface xComponent = new ConcreteXComponent1();
IMyInterface xComponent = new ConcreteXComponentAlternative();

That works great, but obviously requires a recompile -- I'd rather the concrete class was chosen using a value from a config file.

What's the standard pattern for changing concrete classes using a configuration file? Is there standard library I can use that solves this problem for me?

Thanks!

+1  A: 

Try the factory pattern

http://en.wikipedia.org/wiki/Abstract_factory_pattern

danimajo
Yeah I was hoping there was some standard library component out there that implements that pattern for me. I'm trying to avoid writing code that someone else has already written and tested.
Stewart Johnson
+4  A: 

You want to look at IoC containers. (Spring.NET, StructureMap, Windsor, etc.)

Romain Verdier
I just read through the intros to Spring.NET and Windsor -- they look like just the go. Thanks!
Stewart Johnson
+2  A: 

You could use the Activator.CreateInstance method. One of the methods overloads takes a type name and creates an instance of it using the default constructor. Then you can store the type name of the class in your config file and read it from your application.

Rune Grimstad
For some ideas on how to implement this, you may want to check out Abidar (an open-source task scheduler library for ASP.NET). This reads class names from a config file and creates an instance of them at runtime using the Activate.CreateInstance method mentioned above.
Mun
A: 

Using an IoC container will create a pool or collection of your objects that you can dynamically load. The frameworks that Romain suggested will use a configuration file that describes the objects and how they are instantiated.

David Robbins