Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

D — Dependency Inversion

High-level modules depend on abstractions, not low-level concretions. Invert source of concrete creation.

C#


interface IRepository { string Get(int id); }

class SqlRepository : IRepository
{
	public string Get(int id) => "SQL:" + id;
}

class ApiRepository : IRepository
{
	public string Get(int id) => "API:" + id;
}

class Service
{
	readonly IRepository _repo;
	public Service(IRepository repo) { _repo = repo; }
	public string Fetch(int id) => _repo.Get(id);
}

// usage
var s = new Service(new SqlRepository());
var data = s.Fetch(5);
next