I am just getting started with IoC containers so apologies if this is a stupid question.
I have code like the following in an app
internal static class StaticDataHandlerFactory
{
public static IStaticDataHandler CreateHandler(StaticDataUpdate staticDataUpdate)
{
if (staticDataUpdate.Item is StaticDataUpdateOffice)
{
return new OfficeUpdateHandler();
}
if (staticDataUpdate.Item is StaticDataUpdateEmployee)
{
return new EmployeeUpdateHandler();
}
if (staticDataUpdate.Item == null)
{
throw new NotImplementedException(
string.Format("No static data provided"));
}
else
{
throw new NotImplementedException(
string.Format("Unimplemented static data type of {0}", staticDataUpdate.Item.GetType().FullName));
}
}
}
It is basically a simple factory that returns the correct strategy for handling the input data.
Would an IoC container allow me to eliminate code like this? That is to say : would it allow me to dynamically choose a concrete implementation to load based on the type of an input parameter?
Or am I way off course here?
Actually, although it is possible to replace some of the code with an inversion of control system, it's not obvious to me it's a good idea. Dependency injection tends to be best for configuration of systems, not dynamic creation of objects. To put it a different way, the container itself is a huge global variable and as such should appear in much of your code.
As an aside, the code appears to be violating the Law of Demeter. It appears that the parameter should be of type "StaticDataUpdateItem" rather than "StaticDataUpdate". With that observed, there's a pretty strong argument for rewriting this code as a method call on the StaticDataUpdateItem.
I used IoC quite heavily, but dynamic object creation is still better dealt with using an abstract factory pattern. In short, if you don't like the idea of adding a method to the item itself to generate the handle, the code's probably best left the way it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With