.NET: Select concrete classes using config file
-
04-07-2019 - |
Question
(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!
Solution
You want to look at IoC containers. (Spring.NET, StructureMap, Windsor, etc.)
OTHER TIPS
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.
Try the factory pattern
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.