Created
March 26, 2018 02:00
-
-
Save chadmichel/9c8874c081ed961f581d754ac839d603 to your computer and use it in GitHub Desktop.
Constructor Injection Large 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
using System; | |
using System.Linq; | |
namespace DI | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var manager = new OrderManager( | |
new OrderAccessor(), new EmailAccessor()); | |
manager.SendNotification(1); | |
} | |
} | |
class Order | |
{ | |
public int Id { get; set; } | |
public decimal Total { get; set; } | |
} | |
interface IOrderAccessor | |
{ | |
Order Find(int id); | |
} | |
interface IEmailAccessor | |
{ | |
void SendEmail(Order order); | |
} | |
interface IOrderManager | |
{ | |
void SendNotification(int id); | |
} | |
class OrderAccessor : IOrderAccessor | |
{ | |
static Order[] Orders = new Order[] { new Order() { Id = 1, Total = 100.00M } }; | |
public Order Find(int id) | |
{ | |
return Orders.First(o => o.Id == id); | |
} | |
} | |
class EmailAccessor : IEmailAccessor | |
{ | |
public void SendEmail(Order order) | |
{ | |
Console.WriteLine($"ID={order.Id}"); | |
} | |
} | |
class OrderManager : IOrderManager | |
{ | |
IOrderAccessor OrderAccessor { get; set; } | |
IEmailAccessor EmailAccessor { get; set; } | |
public OrderManager(IOrderAccessor orderAccessor, IEmailAccessor emailAccessor) | |
{ | |
OrderAccessor = orderAccessor; | |
EmailAccessor = emailAccessor; | |
} | |
public void SendNotification(int id) | |
{ | |
var order = OrderAccessor.Find(id); | |
EmailAccessor.SendEmail(order); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment