Dependency Injection Basics
Learn .NET Core's built-in dependency injection container and how to use it effectively. This is a foundational concept in cross-platform .NET development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET Core experience. Take your time with each section and practice the examples
65 min•By Priygop Team•Last updated: Feb 2026
What is Dependency Injection?
Dependency Injection (DI) is a design pattern that implements Inversion of Control (IoC) for resolving dependencies. .NET Core has a built-in DI container that makes it easy to manage dependencies throughout your application.
Service Lifetimes
Example
// Transient: New instance every time
services.AddTransient<IMyService, MyService>();
// Scoped: One instance per request (web apps)
services.AddScoped<IMyService, MyService>();
// Singleton: One instance for the entire application
services.AddSingleton<IMyService, MyService>();
// Example implementation
public interface IEmailService
{
Task SendEmailAsync(string to, string subject, string body);
}
public class EmailService : IEmailService
{
public async Task SendEmailAsync(string to, string subject, string body)
{
// Email sending logic
await Task.CompletedTask;
}
}
// Registration
services.AddScoped<IEmailService, EmailService>();Advanced DI Patterns
Example
// Factory pattern
services.AddTransient<Func<string, ILogger>>(provider => key =>
provider.GetService<ILoggerFactory>().CreateLogger(key));
// Options pattern
services.Configure<DatabaseOptions>(configuration.GetSection("Database"));
// Multiple implementations
services.AddTransient<INotificationService, EmailNotificationService>();
services.AddTransient<INotificationService, SmsNotificationService>();
// Decorator pattern
services.AddTransient<INotificationService, LoggingNotificationService>();
services.Decorate<INotificationService, CachingNotificationService>();