Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Service Locator Full Example
using System;
using System.Linq;
namespace DI
{
class Program
{
static void Main(string[] args)
{
var factory = new Factory();
var manager = factory.CreateOrderManager();
manager.SendNotification(1);
}
}
class Factory
{
public IOrderManager CreateOrderManager()
{
return new OrderManager();
}
public IOrderAccessor CreateOrderAccessor()
{
return new OrderAccessor();
}
public IEmailAccessor CreateEmailAccessor()
{
return new EmailAccessor();
}
}
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
{
Factory Factory { get; set; } = new Factory();
public void SendNotification(int id)
{
var order = Factory.CreateOrderAccessor().Find(id);
Factory.CreateEmailAccessor().SendEmail(order);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment