Introduction
In the previous lessons, we separated the solution into layers, defined domain models and DTOs, prepared Entity Framework Core database access, and moved business rules into application services. For these components to work together, the application must create and provide the objects required by each class. For example, if a service creates its repository with the new keyword, the dependency between layers becomes stronger and testing becomes more difficult.
ASP.NET Core solves this problem with its built-in Dependency Injection (DI) mechanism. With DI, classes do not create concrete dependencies themselves. Instead, they receive the interfaces they need through their constructors. During application startup, we define which implementation should satisfy each interface and how long each object should live.
In this lesson, we will register repository and business-service dependencies, compare the Transient, Scoped, and Singleton lifetimes, manage settings for different environments, and use the strongly typed options pattern.
The Dependency Injection idea
The problem with creating dependencies directly
The following approach may work initially, but ProductService is now directly coupled to the concrete ProductRepository class:
public class ProductService
{
private readonly ProductRepository _repository = new ProductRepository();
public ProductService()
{
}
}This design makes it harder to replace the repository, use a fake repository in tests, or manage additional repository dependencies. It also forces the Business layer to know a concrete type from the DataAccess layer.
Receiving dependencies through interfaces
A more flexible design makes the service depend only on the contract it requires:
public class ProductService : IProductService
{
private readonly IProductRepository _repository;
public ProductService(IProductRepository repository)
{
_repository = repository;
}
public async Task<IReadOnlyList<ProductDto>> GetAllAsync()
{
var products = await _repository.GetAllAsync();
return products.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price
}).ToList();
}
}Here, ProductService does not construct the repository. The ASP.NET Core DI container examines the constructor, finds the implementation registered for IProductRepository, and supplies that object automatically.
Registering services in Program.cs
In the minimal hosting model used by .NET 6 and later, service registrations are usually defined in Program.cs. Instead of placing every registration in one file, it is cleaner to group the registrations belonging to each layer in an extension method.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDataAccess(builder.Configuration);
builder.Services.AddBusiness();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();Inside the DataAccess project:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddDataAccess(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
return services;
}
}Inside the Business project:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddBusiness(
this IServiceCollection services)
{
services.AddScoped<IProductService, ProductService>();
services.AddScoped<ICategoryService, CategoryService>();
return services;
}
}This approach keeps Program.cs small and gives each layer a clear registration entry point. To use the extension methods, make sure the required project references and the Microsoft.Extensions.DependencyInjection namespace are available.
Service lifetimes
A DI registration defines not only the interface-to-class mapping but also the lifetime of the object. Choosing the wrong lifetime can cause unnecessary allocations, shared-state bugs, or problems with DbContext usage.
| Lifetime | Behavior | Typical use |
|---|---|---|
Transient | A new instance is created every time the service is requested. | Stateless, lightweight helper classes. |
Scoped | One instance is created for each HTTP request in a web application. | Repositories, business services, and DbContext. |
Singleton | One instance is used for the lifetime of the application. | Thread-safe shared or immutable services. |
Why Scoped is suitable for repositories and DbContext
AddDbContext registers DbContext as scoped by default. During one HTTP request, repositories and services can use the same context instance. Changes are therefore tracked within one request scope, and the context is disposed when the request finishes.
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<IProductService, ProductService>();A singleton service must not directly depend on a scoped repository or DbContext. A long-lived object would be holding a shorter-lived object. This can produce scope validation errors or cause stale data and incorrect state to be shared.
When can Transient be used?
A stateless and inexpensive class such as a price calculator or DTO mapper may be registered as transient:
services.AddTransient<IPriceCalculator, PriceCalculator>();However, a transient lifetime is not automatically the best choice. If a transient class manages disposable resources, the allocation and disposal frequency must be considered.
Things to remember with Singleton
Singleton services are shared by concurrent requests. They must therefore avoid mutable user-specific state and non-thread-safe objects:
services.AddSingleton<IApplicationClock, ApplicationClock>();A singleton should not directly depend on scoped or transient services. In background-processing scenarios, a controlled scope can be created with IServiceScopeFactory, but this should be an intentional design decision rather than a workaround for an incorrect registration.
Environment-specific configuration
An application usually needs different settings in development, testing, and production. ASP.NET Core reads base settings from appsettings.json and can also load appsettings.{Environment}.json. For example, the Development environment commonly loads appsettings.Development.json.
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=ShopDb;Trusted_Connection=True;TrustServerCertificate=True"
},
"ApiSettings": {
"BaseUrl": "https://localhost:7001",
"TimeoutSeconds": 30
}
}{
"ApiSettings": {
"BaseUrl": "https://localhost:7001",
"TimeoutSeconds": 60
}
}Values from the environment-specific file override values from the base file. Sensitive information should not be committed to source control. For local development, use User Secrets; in production, use environment variables or an appropriate secure secret provider.
Reading configuration values directly
For one small setting, IConfiguration may be sufficient:
public class ProductService : IProductService
{
private readonly int _pageSize;
public ProductService(IConfiguration configuration)
{
_pageSize = configuration.GetValue<int>("ApiSettings:PageSize");
}
}However, reading many values this way spreads string keys throughout the application. The options pattern is a better choice for grouped and reusable settings.
Using strongly typed Options
First, create a class that represents the settings:
public sealed class ApiSettings
{
public const string SectionName = "ApiSettings";
public string BaseUrl { get; set; } = string.Empty;
public int TimeoutSeconds { get; set; }
public int PageSize { get; set; }
}Then bind the configuration section to the DI container:
builder.Services
.AddOptions<ApiSettings>()
.Bind(builder.Configuration.GetSection(ApiSettings.SectionName))
.Validate(settings => Uri.TryCreate(
settings.BaseUrl, UriKind.Absolute, out _),
"BaseUrl must be a valid URL.")
.Validate(settings => settings.TimeoutSeconds > 0,
"TimeoutSeconds must be greater than zero.")
.ValidateOnStart();A service can now access the settings through a typed dependency:
using Microsoft.Extensions.Options;
public class ProductService : IProductService
{
private readonly ApiSettings _settings;
public ProductService(IOptions<ApiSettings> options)
{
_settings = options.Value;
}
public int GetPageSize() => _settings.PageSize;
}IOptions<T> is suitable for reading values that are effectively fixed after startup. Use IOptionsSnapshot<T> when values should be recalculated per request, and IOptionsMonitor<T> when a long-lived service must observe reloadable configuration changes. The choice depends on whether the settings can change and on the lifetime of the consuming service.
Step-by-step application flow
- Check the interfaces: Repository and service classes should be exposed through public contracts.
- Register the DbContext: Read the connection string through configuration and call
AddDbContext. - Register repositories: In most web applications, use
AddScopedfor interface-to-implementation mappings. - Register business services: Register services as scoped when they use scoped repositories or a scoped context.
- Bind options: Bind each configuration section to a strongly typed options class.
- Consume dependencies in the API: Ask the controller constructor only for the business interface it needs.
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
private readonly IProductService _service;
public ProductsController(IProductService service)
{
_service = service;
}
[HttpGet]
public async Task<ActionResult<IReadOnlyList<ProductDto>>> GetAll()
{
var products = await _service.GetAllAsync();
return Ok(products);
}
}When a request arrives, the framework creates the controller, resolves IProductService, resolves the repository required by that service, and provides the AppDbContext required by the repository within the same request scope.
Common mistakes
- Forgetting a registration: “Unable to resolve service for type...” usually means an interface has no matching registration.
- Incorrect project references: The API should reference Business, while Business and DataAccess should reference the appropriate abstractions according to the intended dependency direction.
- Making DbContext a singleton:
DbContextis not thread-safe and should not be shared between web requests. - Using a scoped dependency inside a singleton: This creates a lifetime mismatch.
- Misspelling configuration keys: Names such as
ApiSettings:TimeoutSecondsmust match the JSON hierarchy. - Committing secrets: Production connection strings and keys must not be stored in source control.
- Resolving everything through IServiceProvider: The service locator approach hides dependencies. Constructor injection is easier to understand and test.
- Skipping options validation: Invalid settings discovered only during request processing are harder to diagnose. Use
ValidateOnStartfor critical configuration.
Short practice exercise
Create a NotificationSettings options class with SenderName and MaxRetryCount properties. Add a corresponding section to appsettings.json and bind it with AddOptions.
- Create
INotificationServiceandNotificationService. - Register the service with a transient lifetime.
- Inject
IOptions<NotificationSettings>into the service. - Add validation that prevents
MaxRetryCountfrom being negative. - Return the sender name from a controller endpoint through the service.
- Define different sender values in Development and Production files and test the environment selection.
Conclusion
Dependency Injection allows the layers of a 3-tier architecture to depend on contracts rather than concrete classes. When repositories and business services are registered with suitable lifetimes, request scope, DbContext usage, and resource management become safer. Binding environment-specific configuration to typed options classes also prevents string keys from spreading throughout the codebase and allows invalid settings to be detected early.
At this point, the API project can manage the dependencies of the Business and DataAccess layers in a centralized and maintainable way. The next stage can build on this foundation by making API endpoints more reliable through validation, error handling, and communication with the web client.