Reputation: 5326
Ok I am just learning DI. I was going through few pointers in net for understanding it. Then I have made a very small real time scenario just to understand it myself.
I am applying DI constructor injection pattern to compute the discount of a product price for different types of customers. If its an employee, then there is separate discount and if its a normal buyer then it is going to be a separate discount. I don't know if this is appropriate to apply DI in this context or any other better solution/patterns is available. I just compiled the code and I am happy it runs. However, I am not confident about the correctness of this. And would appreciate any corrections on this program as in fine tuning, and or suggestions like better approaches. Also, is it what is really a DI? If this is what is called dependency injection, aren't we hardcoding the class in the static main method? Is it right what am I doing and is it what we do in realtime scenario? It will also help others like me.
class Program
{
public interface IDiscount
{
void Discount(int amount);
}
public class ApplyDiscount : IDiscount
{
public void Discount(int amount)
{
Console.WriteLine("Normal Discount calculated is {0}", amount);
}
}
public class ApplyEmployeeDiscount : IDiscount
{
public void Discount(int amount)
{
Console.WriteLine("Employee Discount calculated is {0}", amount);
}
}
public class Compute
{
public readonly IDiscount discount;
public Compute(IDiscount discount)
{
this.discount = discount;
}
public void ComputeTotal(int productAmount)
{
this.discount.Discount(productAmount);
}
}
static void Main()
{
IDiscount regularDiscount = new ApplyDiscount();
IDiscount employeeDiscount = new ApplyEmployeeDiscount();
Compute c = new Compute(employeeDiscount);
c.ComputeTotal(200);
Console.ReadLine();
}
}
Upvotes: 1
Views: 585
Reputation: 11783
I'll split this into 3 parts:
Yes/No answer, yes, you injected a dependency.
Here's a short blog that will clarify what dependency injection is in a simple (and short) way: Blog by James Shore.
The heavy guns: article by Martin Fowler. Not much to add to this (mind you, long deep article)
Upvotes: 2