Last active
January 28, 2022 23:23
-
-
Save agusputra/8120647 to your computer and use it in GitHub Desktop.
IoC and Dependency Injection Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Program | |
| { | |
| interface IPrinter | |
| { | |
| void Print(); | |
| } | |
| class InjectPrinter : IPrinter | |
| { | |
| public void Print() | |
| { | |
| //InjectPrinter Print | |
| } | |
| } | |
| class LaserPrinter : IPrinter | |
| { | |
| public void Print() | |
| { | |
| //LaserPrinter Print | |
| } | |
| } | |
| //Yang kita harapkan adalah class ini seharusnya hanya bergantung pada INTERFACE IPrinter, | |
| //dan bukan pada implementasi dari IPrinter. | |
| //Sehingga kita bisa memberikan Printer apapun padanya (InjectPrinter atau LaserPrinter). | |
| //Tetapi karena kita tidak melakukan IoC pada class ini, | |
| //akhirnya class ini menjadi tidak fleksibel. | |
| //Class ini terpaksa harus bergantung pada spesifik Printer | |
| //yaitu InjectPrinter. | |
| class EmployeeDependWithSpecificPrinter | |
| { | |
| public void PrintDocument() | |
| { | |
| IPrinter printer = new InjectPrinter(); | |
| printer.Print(); | |
| } | |
| } | |
| //Pada class ini kita menerapkan IoC. | |
| //Sehingga class ini menjadi lebih fleksibel. | |
| //Kita bisa meng-inject Printer yang kita mau. | |
| //Baik dari constructor, maupun dari property injection. | |
| class EmployeeNotDependWithSpecificPrinter | |
| { | |
| public IPrinter Printer { private get; set; } | |
| public EmployeeNotDependWithSpecificPrinter(IPrinter printer) | |
| { | |
| if (printer == null) | |
| { | |
| throw new ArgumentNullException(); | |
| } | |
| Printer = printer; | |
| } | |
| public void PrintDocument() | |
| { | |
| Printer.Print(); | |
| } | |
| } | |
| static void Main() | |
| { | |
| EmployeeDependWithSpecificPrinter employee1 = new EmployeeDependWithSpecificPrinter(); | |
| employee1.PrintDocument(); | |
| //contructor injection | |
| EmployeeNotDependWithSpecificPrinter employee2 = new EmployeeNotDependWithSpecificPrinter(new InjectPrinter()); | |
| employee2.PrintDocument(); | |
| //property injection | |
| employee2.Printer = new LaserPrinter(); | |
| employee2.PrintDocument(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment