Question

This has been bugging me a bit... It is a question regarding Dependency Injection.

The code is trivial and it merely demonstrates the problem:

public static void Main(string[] args)
        {    
            //Take new instance from the app config
            IVehicle vehicle = CreateVehicle(); 

            //inject the new instance
            var mainClass = new GenericClass();
            mainClass.InjectType(vehicle); 

            //call the generic class 
            mainClass.DoSomething(); 
        }

        public static IVehicle CreateVehicle()
        {
            var dynamicType = Type.GetType(ConfigurationManager.AppSettings["ClassName"]);

            var vehicle = Activator.CreateInstance(dynamicType);

            return (IVehicle)vehicle; 
        }

 public class GenericClass : IInjectDependent
    {
        IVehicle vehicleDependent;

        public void DoSomething()
        {
            vehicleDependent.Drive();
            Console.ReadLine();
        }

        public void InjectType(IVehicle vehicle)
        {
            vehicleDependent = vehicle;
        }
    }

 public interface IInjectDependent
    {
        void InjectType(IVehicle vehicle);
    }

Not much going on there.

  1. A quick factory-like method to create a vehicle type (pulled from app config in this case).
  2. The created type is then injected to the 'generic' class via a method implemented with the IInjectDependent
  3. The 'generic' class with the injected type then goes off and calls the logic on the concrete classes (bus, car, ambulance, and whatever class implements the IVehicle interface)

...my question is - the same could be easily achieved with parameterised constructor on the 'generic' class:

 public class GenericClass 
    {
        IVehicle vehicleDependents;

        public GenericClass(IVehicle vehicle)
        {
            vehicleDependent = vehicle; 
        }

        public void DoSomething()
        {
            vehicleDependent.Drive();
            Console.ReadLine();
        }  
    }

This way we don't need the interface and the method that comes with it. We simply ask for the type in the constructor.

So what are the benefits of using interface over constructor in this case? Thanks.

Was it helpful?

Solution

There is a post about Dependency Injection(DI) here. See @Thiago Arrais's answer, in particular.

It seems nice if the constructors are minimal, and dependencies are specified as interfaces. This means other code can easily instantiate your class, and also supply its own impementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top