Dependency Injection, bağımlılığı minimuma indirdiğimiz bir tasarım prensibidir. Bağımlılıktan kasıt, örneğin içeriği farklı ama yaptığı işlem başlıkları aynı olan bir kaç methodumuz var diyelim. Örneğin database’imize veri ekleme işlemi olsun, bu MsSql’e de veri ekleme olabilir MySql’e de veya programı yazdıktan sonra yarın bir gün bizden PostgreSql’e eklememiz de istenebilir. Burada bütün bu Class’ları new’lemek (instance almak) çok karmaşık ve zaman kaybı olabilir.
O yüzden bu Class’ların method isimlerini (imzalarını) tutan bir Interface oluştururuz. Class’larımızı bu interface’den implemente ederiz. Çağıracağımız zaman da:
IMyInterface myInterface=new MsSql();
ya da
IMyInterface myInterface=new MySql();
Aynı şekilde soyuttan somut tutan bir yapı oluşturabiliriz. Bu tasarım kalıbına Dependency Injection denir ve SOLID tasarım prensibinin son harfini temsil eder.
public class ExampleForDependencyInjectionController : Controller
{
public IActionResult Index()
{
IGet get = new GetWithAdoNet();
get.GetName("Example");
IGet get1 = new GetWithEntity();
get.GetName("Example");
IGet get2 = new GetWithDapper();
get.GetName("Example");
return View();
}
}
public interface IGet
{
string GetName(string name);
}
public class GetWithAdoNet : IGet
{
public string GetName(string name)
{
//Ado.net codes
return (name + "was get with AdoNet");
}
}
public class GetWithEntity : IGet
{
public string GetName(string name)
{
//EntityFramework Codes
return (name + "was get with Entity Framework");
}
}
public class GetWithDapper : IGet
{
public string GetName(string name)
{
//Dapper Codes
return (name + "was get with Dapper");
}
}

Yorum bırakın