I am currently working on a project where I need to create objects at runtime based on a configuration file.
Project example
Here is a simplified example of the project I am working on.
Every object created must implement a specific interface, let it be called the IObjectInterface for the example purpose :
public interface IObjectInterface
{
void DoSomething();
}
Let’s assume that I have several classes that implement this interface, each having a specific implementation, and multiple other properties relevant to the specific type :
public class SimpleObject : IObjectInterface
{
public void DoSomething()
{
Console.WriteLine("SimpleObject did something");
}
}
public class ComplexObject : IObjectInterface
{
public string ObjectName { get; set; }
public void DoSomething()
{
Console.WriteLine("The ComplexObject named {0} did something", this.ObjectName);
}
}
public class VeryComplexObject : IObjectInterface
{
public string ObjectName { get; set; }
public bool CanDoSomething { get; set; }
public void DoSomething()
{
if (this.CanDoSomething)
{
Console.WriteLine("The ComplexObject named {0} did something", this.ObjectName);
}
else
{
Console.WriteLine("The ComplexObject named {0} tried to do something, but was not allowed to", this.ObjectName);
}
}
}
I need to be able to create a IObjectInterface object corresponding to a specific Id using the ObjectBuilder class :
public class ObjectBuilder
{
IObjectInterface BuildObject(string objectId)
{
// Build object here based on provided Id
}
}
What I am looking for is a way to specify, in a configuration file, the correct implementation of IObjectInterface that should be created, and the parameter values associated to the specific type.
The ideal configuration file should look like this :
<objects>
<object id="Simple">
<objectInterface type="SimpleObject" />
</object>
<object id="Complex">
<objectInterface type="ComplexObject">
<ObjectName value="MyObject" />
</objectInterface>
</object>
</objects>
I think I should be able to manage the object instantiation part, but I don’t really see how I can manage the initialization of the instances with clean code.
- Do you have some leads on how I can implement such a configuration file ?
- How can I easily create the final instances of the needed objects and initialize them with the parameters provided in the configuration file ?
- Are there any frameworks that could help me implementing a solution to my problem ?
Sounds like IOC for me. StructureMap NInject Microsoft Extensibility Framework