Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an IoC container replace the use of Factories

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?

like image 974
ChrisCa Avatar asked Feb 03 '23 12:02

ChrisCa


1 Answers

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.

like image 151
Julian Birch Avatar answered Feb 06 '23 01:02

Julian Birch