Dependency Injection Servisleri
Nedir?
Dependency Injection (DI), ASP.NET Core'da servisleri otomatik olarak inject etme mekanizmasidır.
Yaygın DI Servisleri
1. ILogger<T> - Loglama
public class UserService
{
private readonly ILogger<UserService> _logger;
public UserService(ILogger<UserService> logger)
{
_logger = logger;
}
public void CreateUser(string name)
{
_logger.LogInformation($"Kullanıcı oluşturuluyor: {name}");
}
}
2. IConfiguration - Ayarlar
public class AppSettings
{
private readonly IConfiguration _config;
public AppSettings(IConfiguration config)
{
_config = config;
}
public string GetConnectionString()
{
return _config.GetConnectionString("DefaultConnection");
}
}
3. DbContext - Veritabanı
public class UserRepository
{
private readonly ApplicationDbContext _dbContext;
public UserRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public void AddUser(User user)
{
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
}
}
4. IHttpClientFactory - HTTP Istekleri
public class ApiClient
{
private readonly IHttpClientFactory _httpClientFactory;
public ApiClient(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<string> GetDataAsync()
{
var client = _httpClientFactory.CreateClient();
var response = await client.GetAsync("https://api.example.com/data");
return await response.Content.ReadAsStringAsync();
}
}
5. IOptions<T> - Strongly Typed Ayarlar
public class AppOptions
{
public string ApiUrl { get; set; }
public int Timeout { get; set; }
}
public class MyService
{
private readonly IOptions<AppOptions> _options;
public MyService(IOptions<AppOptions> options)
{
_options = options;
}
public void DoSomething()
{
var apiUrl = _options.Value.ApiUrl;
}
}
6. IMemoryCache - Bellek Cache
public class CachedUserService
{
private readonly IMemoryCache _cache;
public CachedUserService(IMemoryCache cache)
{
_cache = cache;
}
public User GetUser(int id)
{
if (!_cache.TryGetValue($"user_{id}", out User user))
{
user = new User { Id = id, Name = "Ali" };
_cache.Set($"user_{id}", user, TimeSpan.FromMinutes(10));
}
return user;
}
}
7. IDistributedCache - Redis Cache
public class DistributedCacheService
{
private readonly IDistributedCache _cache;
public DistributedCacheService(IDistributedCache cache)
{
_cache = cache;
}
public async Task SetValueAsync(string key, string value)
{
await _cache.SetStringAsync(key, value, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1)
});
}
}
8. IWebHostEnvironment - Ortam Bilgisi
public class EnvironmentService
{
private readonly IWebHostEnvironment _env;
public EnvironmentService(IWebHostEnvironment env)
{
_env = env;
}
public void CheckEnvironment()
{
if (_env.IsDevelopment())
{
Console.WriteLine("Development ortamı");
}
else if (_env.IsProduction())
{
Console.WriteLine("Production ortamı");
}
}
}
9. IServiceProvider - Servis Çözme
public class ServiceLocator
{
private readonly IServiceProvider _serviceProvider;
public ServiceLocator(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public T GetService<T>() where T : class
{
return _serviceProvider.GetRequiredService<T>();
}
}
DI Kayıt Yöntemleri (Startup.cs / Program.cs)
Transient (Her Seferinde Yeni)
services.AddTransient<IUserService, UserService>();
Scoped (Request Başına Bir)
services.AddScoped<IRepository, Repository>();
Singleton (Uygulama Boyunca Bir)
services.AddSingleton<IConfiguration>(config);
Servisleri Kayıt Etme (Program.cs)
var builder = WebApplication.CreateBuilder(args);
// Servisleri kayıt et
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IRepository, UserRepository>();
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
builder.Services.AddLogging();
builder.Services.AddDbContext<ApplicationDbContext>();
var app = builder.Build();
app.Run();
Servisleri Controller'da Kullanma
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
private readonly ILogger<UsersController> _logger;
public UsersController(IUserService userService, ILogger<UsersController> logger)
{
_userService = userService;
_logger = logger;
}
[HttpGet("{id}")]
public ActionResult<User> GetUser(int id)
{
_logger.LogInformation($"Kullanıcı {id} alınıyor");
var user = _userService.GetUser(id);
return Ok(user);
}
}
| Servis / Interface | Ne İşe Yarar |
|---|---|
IConfiguration | Uygulama ayarlarını ve connection string’leri okumak |
IMemoryCache | Uygulama içinde geçici veri (cache) tutmak |
IDistributedCache | Redis veya SQL tabanlı dağıtık cache kullanmak |
`ILogger<T>` | Loglama yapmak |
DbContext / IDbContext | Entity Framework Core ile veritabanı işlemleri yapmak |
`IOptions<T>` | Strongly typed ayarları almak (config binding) |
IHttpClientFactory | HTTP client oluşturmak ve yönetmek |
IWebHostEnvironment | Ortam bilgisi almak (Development, Production vb.) |
`IHubContext<THub>` | SignalR hub üzerinden client ile iletişim sağlamak |
IServiceProvider | DI container üzerinden servis çözmek (runtime’da almak) |
`UserManager<TUser>` | ASP.NET Core Identity ile kullanıcı yönetimi yapmak |
`SignInManager<TUser>` | ASP.NET Core Identity ile kullanıcı giriş işlemleri yapmak |
`RoleManager<TRole>` | ASP.NET Core Identity ile roller yönetmek |
