Reputation: 1013
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.
...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.
Upvotes: 0
Views: 2817
Reputation: 1098
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.
Upvotes: 1