IoC Prensibi Nedir? Örnek Bir Proje ile Kullanımı ve Avantajları

  • Loosely coupled (bağımlılığı az) sınıflar oluşturma
  • Kolay unit test yazma
  • Yönetilebilirlik
  • Modüler programlar
  • Farklı implementasyonlar arası kolay geçiş
public class OracleConnection { 
public string GetData() {
return "Oracle";
}
}
public class MsSQLConnection {
public string GetData() {
return "MsSQL";
}
}
public class ConnectionHelper { 
private OracleConnection _oConnection;
public ConnectionHelper() {
_oConnection = new OracleConnection();
}
public string GetData() {
return _oConnection.GetData();
}
}
public class ConnectionFactory {
public static OracleConnection GetCon() {
return new OracleConnection();
}
}
public class ConnectionHelper {
private OracleConnection _oConnection;
public ConnectionHelper() {
_oConnection = ConnectionFactory.GetCon();
}
public string GetData() {
return _oConnection.GetData();
}
}
public interface IConnection {
string GetData();
}
public class OracleConnection : IConnection {
public string GetData() {
return "Oracle";
}
}
public class MsSQLConnection : IConnection {
public string GetData() {
return "MsSQL";
}
}
public class ConnectionFactory {
public static IConnection GetCon() {
return new OracleConnection();
}
}
public class ConnectionHelper { 
private IConnection _connection;
public ConnectionHelper() {
_connection = ConnectionFactory.GetCon();
}
public string GetData() {
return _connection.GetData();
}
}
public class ConnectionHelper {
private IConnection _connection;
public ConnectionHelper(IConnection connection) {
_connection = connection;
}
public string GetData() {
return _connection.GetData();
}
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase {
private ConnectionHelper _connectionHelper;
public ValuesController() {
_connectionHelper =
new ConnectionHelper(new MsSQLConnection());
}
[HttpGet]
public ActionResult Get() {
return _connectionHelper.GetData();
}
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase {
private readonly IConnection _connection;
public ValuesController(IConnection connection) {
_connection = connection;
}
[HttpGet]
public ActionResult Get() {
return _connection.GetData();
}
}

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store