Intermediate 48 min read

Dependency Injection

IServiceCollection, lifetimes, scopes.

1. About

Understand how Dependency Injection makes .NET applications loosely coupled, testable, maintainable, and production-ready.

PropertyDetails
Category.NET Fundamentals
DifficultyIntermediate
Estimated Reading Time25–35 minutes
TechnologyC#, ASP.NET Core, .NET 9+
Previous TopicGeneric Host
Next TopicService Lifetime

Prerequisites

Before studying this module, you should understand:

  • C# classes, objects, and constructors.
  • Interfaces and their implementations.
  • Basic object-oriented programming.
  • ASP.NET Core application structure.
  • The Generic Host and Program.cs.

Learning Outcomes

After completing this module, you will be able to:

  • Explain Dependency Injection (DI) and why it exists.
  • Understand the relationship between interfaces, services, and consumers.
  • Register services in the ASP.NET Core dependency injection container.
  • Use constructor injection in controllers and other classes.
  • Understand how ASP.NET Core resolves dependencies.
  • Differentiate DI from Dependency Inversion and the Service Locator pattern.
  • Recognize common DI mistakes and avoid them in production.
  • Write unit tests using dependency injection and mock implementations.
  • Answer common DI interview questions.
  • Understand the basic purpose of service lifetimes before studying them in detail in the next module.

2. Introduction

What is Dependency Injection?

Dependency Injection is a design technique in which a class receives the objects it needs from an external source instead of creating those objects itself.

Let's understand this with a simple example.

Suppose you are developing an e-commerce application. You have a ProductsController that needs a ProductService to retrieve product information.

Without Dependency Injection, you might write:

public class ProductsController
{
    private readonly ProductService _productService;

    public ProductsController()
    {
        // The controller creates its own dependency.
        _productService = new ProductService();
    }

    public void GetProducts()
    {
        _productService.GetAllProducts();
    }
}

This code works, but the controller is directly responsible for creating its service.

What happens if ProductService later requires a database repository, a logger, and a caching service?

The controller may need to know how to construct all those objects. As the application grows, the complexity increases.

Dependency Injection solves this problem by allowing the controller to receive its required service from outside.

public class ProductsController
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    public void GetProducts()
    {
        _productService.GetAllProducts();
    }
}

Now the controller does not create the service. It declares what it needs, and ASP.NET Core supplies the dependency.

The central idea: A class should focus on its own responsibility rather than managing the creation of all the objects it depends on.

Why does Dependency Injection exist?

Dependency Injection helps solve several common software design problems.

1. Tight coupling

When one class directly creates another class, the two classes become closely connected.

2. Difficult testing

A class that creates its own database service may require a real database even when you only want to test its business logic.

3. Difficult maintenance

Replacing an implementation can require changes in several different classes.

4. Repeated object creation logic

Multiple classes may duplicate the logic needed to create the same dependency.

5. Complex object construction

Real-world services often depend on other services, creating a chain of dependencies.

DI centralizes dependency registration and resolution instead of spreading object creation across the application.

Why should .NET developers learn DI?

Dependency Injection is a fundamental part of modern ASP.NET Core development.

It is used with:

  • Controllers and minimal API endpoints.
  • Business services.
  • Database repositories.
  • Entity Framework Core.
  • Logging.
  • Authentication and authorization services.
  • HTTP clients.
  • Background services.
  • Configuration and caching components.

ASP.NET Core provides a built-in DI container, so developers can use DI without installing a third-party container for ordinary application requirements.


3. Real-Life Analogy: A Restaurant

Imagine that you own a restaurant.

A customer places an order with a waiter. The waiter does not grow vegetables, manufacture cooking equipment, or construct an oven. Instead, the waiter coordinates with the kitchen, where the required resources and people are available.

Now map this scenario to software development.

RestaurantASP.NET Core application
Customer requestHTTP request
WaiterController or API endpoint
Kitchen serviceBusiness service
Chef's recipe contractInterface
Actual chefConcrete implementation
Restaurant managementDI container and service registration
Kitchen equipmentSupporting dependencies

Suppose a customer orders a pizza. The waiter requests pizza preparation from the kitchen rather than building an oven and preparing every ingredient personally.

Similarly, a controller should request a product service rather than construct its own database access infrastructure.

The controller depends on a contract that describes what it needs. The application determines which implementation will fulfill that contract.

Remember: DI is like receiving the resources you need to perform a task instead of being responsible for manufacturing every resource yourself.

One important distinction: DI does not automatically implement business logic. It supplies the objects that contain that logic.


4. Architecture Diagram

The following diagram shows how Dependency Injection connects an incoming request to the application services.

How to read the diagram

  1. Program.cs registers the application's services.
  2. The DI container uses those registrations to resolve dependencies.
  3. The controller receives an IProductService.
  4. The service implementation uses an IProductRepository.
  5. The repository interacts with the database.
  6. The controller does not need to know how the repository or database connection is constructed.

The dashed arrows represent implementation relationships or dependency resolution, not HTTP requests.


5. Concept Explanation

5.1 What is a dependency?

A dependency is an object or service that another class needs to perform its work.

Consider this example:

public class ProductService
{
    public void GetProducts()
    {
        Console.WriteLine("Fetching products...");
    }
}

public class ProductsController
{
    private readonly ProductService _productService;

    public ProductsController(ProductService productService)
    {
        _productService = productService;
    }
}

Here, ProductsController depends on ProductService.

The controller cannot perform its intended product-related work without the functionality provided by that service.

Dependencies are not limited to services. They can include repositories, loggers, HTTP clients, configuration objects, and other required components.

5.2 What is tight coupling?

Tight coupling occurs when a class is strongly dependent on a particular implementation.

Consider:

public class ProductService
{
    public string GetProductName()
    {
        return "Laptop";
    }
}

public class ProductsController
{
    private readonly ProductService _service = new ProductService();

    public string GetProduct()
    {
        return _service.GetProductName();
    }
}

The controller directly creates ProductService.

If you later introduce CachedProductService, the controller's construction and implementation choices may need to change.

This becomes more problematic when many controllers create the same implementation independently.

5.3 What is loose coupling?

Loose coupling means that classes depend on well-defined contracts rather than being tightly tied to concrete implementations.

An interface can provide that contract.

public interface IProductService
{
    string GetProductName();
}

public class ProductService : IProductService
{
    public string GetProductName()
    {
        return "Laptop";
    }
}

The controller can now depend on IProductService.

public class ProductsController
{
    private readonly IProductService _service;

    public ProductsController(IProductService service)
    {
        _service = service;
    }

    public string GetProduct()
    {
        return _service.GetProductName();
    }
}

The controller does not need to know which class implements IProductService.

This makes it easier to substitute implementations for testing, development, or different business requirements.

Important: An interface is not mandatory for every dependency. You can inject concrete classes, too. Interfaces are especially useful when you need abstraction, multiple implementations, or straightforward substitution in tests.

5.4 What is the DI container?

A DI container is the component responsible for managing registered dependencies and supplying them when requested.

In ASP.NET Core, the built-in container is configured through IServiceCollection and accessed through IServiceProvider.

The container supports three important operations:

  1. Registration: Tell the container which services it can provide.
  2. Resolution: Request a service and obtain an instance with its required dependencies.
  3. Lifetime management: Control how instances are created and reused.

For example:

builder.Services.AddScoped<IProductService, ProductService>();

This registration tells ASP.NET Core how to provide IProductService by using ProductService.

It does not mean that every service instance is created immediately when the application starts. In ordinary use, the instance is created when the dependency is resolved, subject to its registration and lifetime.

5.5 What is service registration?

Service registration is the process of describing which implementation should be provided for a requested service type.

ASP.NET Core commonly uses the builder.Services collection in Program.cs.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Register application dependencies.
builder.Services.AddScoped<IProductService, ProductService>();

var app = builder.Build();

app.MapControllers();

app.Run();

This is where the application tells the DI container about the relationship between IProductService and ProductService.

If a controller requests IProductService, the container can use this registration to provide a ProductService.

5.6 What is constructor injection?

Constructor injection is the most common DI technique in ASP.NET Core.

A class declares its dependencies as constructor parameters.

public class ProductsController
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
}

The controller communicates its requirement through the constructor.

ASP.NET Core resolves the dependency and passes it to the constructor when it creates the controller.

Constructor injection has several benefits:

  • Dependencies are visible.
  • Required dependencies can be validated during object construction.
  • Dependencies can be stored in readonly fields.
  • Tests can supply fake or mock implementations.
  • The class is less responsible for object creation.

5.7 Types of Dependency Injection

Three commonly discussed injection techniques are constructor injection, property injection, and method injection.

TechniqueHow it worksTypical ASP.NET Core usage
Constructor injectionDependencies are supplied through constructor parameters.Preferred for required dependencies.
Property injectionA dependency is assigned to a property.Not built into the default ASP.NET Core DI container as automatic property injection.
Method injectionA dependency is supplied through a method parameter.Useful for action-specific dependencies, such as controller action parameters.

Example of constructor injection:

public class ProductService
{
    private readonly ILogger<ProductService> _logger;

    public ProductService(ILogger<ProductService> logger)
    {
        _logger = logger;
    }
}

Example of method injection in a controller action:

[ApiController]
[Route("api/[controller]")]
public class ReportsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetReport(
        [FromServices] IReportService reportService)
    {
        return Ok(reportService.GenerateReport());
    }
}

The [FromServices] attribute tells ASP.NET Core to obtain that action parameter from the service container.

Best practice: Use constructor injection for required dependencies. Use action-level injection when a dependency is genuinely needed only by a specific action. Avoid designing classes around large collections of optional dependencies.

5.8 What is Dependency Inversion?

Dependency Inversion is a design principle associated with SOLID.

It recommends that high-level business logic should not depend directly on low-level implementation details. Both should depend on abstractions where appropriate.

For example:

  • High-level component: ProductService.
  • Abstraction: IProductRepository.
  • Low-level component: ProductRepository.
public interface IProductRepository
{
    IEnumerable<string> GetAll();
}

public class ProductRepository : IProductRepository
{
    public IEnumerable<string> GetAll()
    {
        return ["Laptop", "Phone", "Tablet"];
    }
}

public class ProductService : IProductService
{
    private readonly IProductRepository _repository;

    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }

    public string GetProductName()
    {
        return _repository.GetAll().First();
    }
}

Dependency Inversion is a design principle. Dependency Injection is a technique that helps supply the required implementations.

They are related, but they are not the same concept.

5.9 DI versus object creation

DI does not eliminate object creation. It moves responsibility for constructing and supplying dependencies away from the consuming class.

Without DI:

var service = new ProductService();

With DI:

public ProductsController(IProductService service)
{
    _service = service;
}

The container may still create the ProductService object. The important difference is who is responsible for constructing and supplying it.

5.10 Is an interface required for DI?

No.

You can register a concrete service:

builder.Services.AddScoped<ProductService>();

Then inject it directly:

public class ProductsController
{
    private readonly ProductService _service;

    public ProductsController(ProductService service)
    {
        _service = service;
    }
}

This is valid DI.

However, using an interface often provides more flexibility when the consumer should not depend on a specific implementation.

5.11 What happens if a dependency is not registered?

Suppose the controller requests IProductService, but no matching service registration exists.

The built-in container generally cannot resolve the required dependency, so the application throws an exception when it tries to construct the controller or other consumer.

Typical error:

InvalidOperationException:
Unable to resolve service for type
'IProductService' while attempting to activate
'ProductsController'.

How to fix it:

builder.Services.AddScoped<IProductService, ProductService>();

Also verify that the implementation is concrete, accessible, and has all its own required dependencies registered.

5.12 What is the difference between DI and a service locator?

With DI, dependencies are explicitly declared, usually in a constructor.

With the Service Locator pattern, a class requests dependencies from a general-purpose provider whenever it needs them.

Example of service locator usage:

public class ProductsController
{
    private readonly IServiceProvider _provider;

    public ProductsController(IServiceProvider provider)
    {
        _provider = provider;
    }

    public void GetProducts()
    {
        var service = _provider.GetRequiredService<IProductService>();

        service.GetProductName();
    }
}

Although this can work, it hides the controller's actual dependencies from its constructor signature.

Prefer direct constructor injection for ordinary application services. Reserve direct IServiceProvider usage for infrastructure scenarios where dynamic resolution is genuinely necessary.


6. Important Terminology

TermMeaningExample
DependencyAn object required by another class.ProductService
ConsumerA class that uses a dependency.ProductsController
InterfaceA contract defining required members.IProductService
ImplementationA class that fulfills a contract.ProductService
DI containerComponent that resolves registered services.ASP.NET Core's built-in container
Service registrationConfiguring how a service is provided.AddScoped<IProductService, ProductService>()
ResolutionObtaining a service and its dependencies.Resolving IProductService
Constructor injectionSupplying dependencies through a constructor.ProductsController(IProductService service)
Composition rootThe application area where dependencies are assembled.Program.cs
AbstractionA contract that hides implementation details.IProductRepository
CouplingThe degree of dependency between components.Controller tied directly to SQL implementation
Dependency InversionA SOLID principle encouraging dependence on abstractions.Business service depends on repository interface
Service lifetimeRules governing instance creation and reuse.Scoped or Singleton registration
Circular dependencyTwo or more components indirectly depend on each other.Service A → Service B → Service A
Service providerObject that supplies registered services.IServiceProvider

7. How It Works Internally

7.1 The workflow

ASP.NET Core uses the registrations in its service collection to build the application's service provider.

When a request requires a controller, the framework asks the container to provide an instance. The container inspects the controller's constructor and resolves its required dependencies.

Consider this dependency chain:

ProductsController
       |
       v
  IProductService
       |
       v
   ProductService
       |
       v
 IProductRepository
       |
       v
  ProductRepository

The container must be able to resolve the complete chain.

7.2 Step-by-step execution

Step 1: Create the builder

var builder = WebApplication.CreateBuilder(args);

The application initializes the builder and its configuration, hosting environment, logging, and service collection.

Step 2: Register dependencies

builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();

The application declares how the interfaces will be fulfilled.

Step 3: Build the application

var app = builder.Build();

The application builds its service provider and hosting pipeline.

Step 4: Receive an HTTP request

A client requests:

GET /api/products

Step 5: Activate the controller

ASP.NET Core determines the endpoint and creates the controller instance when required.

Step 6: Resolve constructor dependencies

The DI container finds the registration for IProductService and creates or obtains the required implementation.

Step 7: Resolve nested dependencies

If ProductService requires IProductRepository, the container resolves that dependency too.

Step 8: Execute business logic

The controller calls the service, which obtains the requested data through the repository.

Step 9: Return the response

The controller returns an HTTP response to the client.

7.3 Sequence diagram

The diagram is a conceptual illustration. The exact sequence of framework calls and object activation depends on the application and its registered services.

7.4 Does DI create all objects at startup?

No.

Service registrations describe how services should be provided. Many services are instantiated only when first resolved.

Some services can be instantiated during startup or by framework initialization, depending on how they are registered and used.

The container does not ordinarily instantiate every registered service simply because its registration exists.

7.5 What is constructor selection?

When a class has a single public constructor, the default container can generally resolve it if all required parameters are resolvable.

When multiple public constructors are present, constructor selection rules matter. The container generally chooses the applicable constructor with the most parameters it can resolve, subject to ambiguity and other constraints.

If constructor selection becomes ambiguous, resolution can fail.

Best practice: Keep constructors clear and avoid multiple public constructors that are simultaneously resolvable.


8. Syntax

Consider this registration:

builder.Services.AddScoped<IProductService, ProductService>();

Let's understand each part.

SyntaxMeaning
builderThe object used to configure the ASP.NET Core application.
ServicesThe service collection used to register dependencies.
AddScopedRegisters a service with a scoped lifetime.
IProductServiceThe service contract requested by consumers.
ProductServiceThe implementation supplied for the contract.
()Invokes the registration method.
;Ends the C# statement.

Common registration methods

builder.Services.AddTransient<IEmailService, EmailService>();

builder.Services.AddScoped<IProductService, ProductService>();

builder.Services.AddSingleton<IAppSettingsCache, AppSettingsCache>();

All three methods register services, but their lifetime behavior differs.

MethodBasic behavior
AddTransientRequests for the service generally create new instances.
AddScopedReuses the same instance within a scope.
AddSingletonReuses one instance from the relevant service provider.

The precise behavior of each lifetime, disposal, nested dependencies, and lifetime mismatch rules will be covered in the next module, Service Lifetime.

Registering a concrete class

builder.Services.AddScoped<ProductService>();

This registers ProductService as a service that can be requested by its concrete type.

It does not automatically register IProductService as an alias for ProductService.

If the controller requests IProductService, register that mapping explicitly:

builder.Services.AddScoped<IProductService, ProductService>();

Registering a factory

You can also register a service using a factory when construction requires a small amount of custom logic.

builder.Services.AddScoped<IProductService>(serviceProvider =>
{
    var logger = serviceProvider
        .GetRequiredService<ILogger<ProductService>>();

    return new ProductService(logger);
});

In most ordinary scenarios, constructor injection and direct type registration are simpler and should be preferred.


9. Code Examples

9.1 Simple example

Let's create a notification service.

Step 1: Create an interface

public interface INotificationService
{
    string SendNotification();
}

The interface defines what the notification service can do without specifying how it does it.

Step 2: Implement the interface

public class NotificationService : INotificationService
{
    public string SendNotification()
    {
        return "Notification sent successfully.";
    }
}

Step 3: Register the service

In Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddScoped<
    INotificationService,
    NotificationService>();

var app = builder.Build();

app.MapControllers();

app.Run();

Step 4: Inject the service

[ApiController]
[Route("api/[controller]")]
public class NotificationsController : ControllerBase
{
    private readonly INotificationService _notificationService;

    public NotificationsController(
        INotificationService notificationService)
    {
        _notificationService = notificationService;
    }

    [HttpGet]
    public IActionResult Send()
    {
        var message = _notificationService.SendNotification();

        return Ok(message);
    }
}

Test the endpoint:

GET /api/notifications

Expected response:

"Notification sent successfully."

The exact response representation depends on the application's content negotiation and serialization settings.

What did we achieve?

  • The controller does not create NotificationService.
  • The controller depends on an interface.
  • ASP.NET Core resolves the implementation.
  • The service can be substituted with another implementation without changing the controller's dependency contract.

9.2 Intermediate example: Product service and repository

Now let's implement a more realistic application flow.

Step 1: Define the repository contract

public interface IProductRepository
{
    IEnumerable<string> GetAllProducts();
}

Step 2: Implement the repository

For this demonstration, use in-memory data rather than a real database.

public class ProductRepository : IProductRepository
{
    private readonly List<string> _products =
    [
        "Laptop",
        "Mobile",
        "Keyboard"
    ];

    public IEnumerable<string> GetAllProducts()
    {
        return _products;
    }
}

Step 3: Define the service contract

public interface IProductService
{
    IEnumerable<string> GetProducts();
}

Step 4: Implement the business service

public class ProductService : IProductService
{
    private readonly IProductRepository _repository;

    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }

    public IEnumerable<string> GetProducts()
    {
        // Business logic can be added here.
        return _repository.GetAllProducts();
    }
}

Step 5: Register both dependencies

builder.Services.AddScoped<
    IProductRepository,
    ProductRepository>();

builder.Services.AddScoped<
    IProductService,
    ProductService>();

Step 6: Inject the service into the controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public IActionResult GetProducts()
    {
        return Ok(_productService.GetProducts());
    }
}

Expected response:

[
  "Laptop",
  "Mobile",
  "Keyboard"
]

Why is this architecture useful?

The controller handles HTTP concerns, the service handles business logic, and the repository handles data access.

If you later replace the in-memory repository with an Entity Framework Core implementation, the controller can continue using the same IProductService contract.

You may need to change service registrations and implementation details, but the controller does not need to know how the data is stored.

9.3 Production example: Product API with logging and EF Core

The following example demonstrates the structure of a production-oriented API. It uses Entity Framework Core, constructor injection, asynchronous database access, logging, and explicit dependency registration.

For this example, install the SQL Server EF Core provider compatible with your selected .NET 9 application:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Entity

public class Product
{
    public int Id { get; set; }

    public required string Name { get; set; }

    public decimal Price { get; set; }
}

DbContext

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products => Set<Product>();
}

Repository contract

public interface IProductRepository
{
    Task<List<Product>> GetAllAsync(
        CancellationToken cancellationToken);
}

Repository implementation

using Microsoft.EntityFrameworkCore;

public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _dbContext;

    public ProductRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public Task<List<Product>> GetAllAsync(
        CancellationToken cancellationToken)
    {
        return _dbContext.Products
            .AsNoTracking()
            .OrderBy(product => product.Name)
            .ToListAsync(cancellationToken);
    }
}

AsNoTracking() is appropriate for this read-only query because the returned entities do not need EF Core change tracking.

Service contract

public interface IProductService
{
    Task<List<Product>> GetProductsAsync(
        CancellationToken cancellationToken);
}

Service implementation

using Microsoft.Extensions.Logging;

public class ProductService : IProductService
{
    private readonly IProductRepository _repository;
    private readonly ILogger<ProductService> _logger;

    public ProductService(
        IProductRepository repository,
        ILogger<ProductService> logger)
    {
        _repository = repository;
        _logger = logger;
    }

    public async Task<List<Product>> GetProductsAsync(
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Retrieving products from the database.");

        return await _repository.GetAllAsync(
            cancellationToken);
    }
}

Controller

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet]
    public async Task<ActionResult<List<Product>>> GetProducts(
        CancellationToken cancellationToken)
    {
        var products = await _productService.GetProductsAsync(
            cancellationToken);

        return Ok(products);
    }
}

Program.cs

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Configure the database connection using configuration.
var connectionString =
    builder.Configuration.GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException(
        "DefaultConnection is not configured.");

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

// Register application dependencies.
builder.Services.AddScoped<
    IProductRepository,
    ProductRepository>();

builder.Services.AddScoped<
    IProductService,
    ProductService>();

var app = builder.Build();

app.MapControllers();

app.Run();

Configuration

Store the connection string in an appropriate configuration source, such as user secrets during local development or a secure deployment configuration.

For example, the configuration key is:

ConnectionStrings:DefaultConnection

Do not commit real production credentials to source control.

Before running the endpoint, configure the database schema and apply the necessary EF Core migrations.

Why is this production-oriented?

  • Constructor injection makes dependencies explicit.
  • EF Core manages database operations through AppDbContext.
  • The repository uses asynchronous I/O.
  • Cancellation tokens can help stop database work when a request is cancelled.
  • Logging provides operational visibility.
  • Configuration separates environment-specific settings from application code.
  • Read-only queries avoid unnecessary change tracking.

This is a foundation, not a complete production system. A real application may also require DTOs, validation, centralized exception handling, authentication, authorization, pagination, and appropriate database migrations.


10. Folder Structure

A simple layered application might use this structure:

ProductApi/
│
├── Controllers/
│   └── ProductsController.cs
│
├── Models/
│   └── Product.cs
│
├── Data/
│   └── AppDbContext.cs
│
├── Repositories/
│   ├── IProductRepository.cs
│   └── ProductRepository.cs
│
├── Services/
│   ├── IProductService.cs
│   └── ProductService.cs
│
├── appsettings.json
├── Program.cs
└── ProductApi.csproj

Responsibility of each folder

FolderResponsibility
ControllersReceives HTTP requests and returns HTTP responses.
ModelsContains application or persistence model classes.
DataContains the EF Core database context and related data configuration.
RepositoriesContains data access abstractions and implementations.
ServicesContains business logic abstractions and implementations.
Program.csConfigures services and the application pipeline.

For a small application, these folders can live in one project. Larger systems may separate application, domain, infrastructure, and API concerns into different projects.

Do not create additional layers merely to follow a pattern. Introduce abstractions when they provide useful separation, testability, or flexibility.


11. Execution Flow

Let's trace the production example when a client requests GET /api/products.

Step 1: Application starts

var builder = WebApplication.CreateBuilder(args);

The builder prepares the host and service collection.

Step 2: Controllers are registered

builder.Services.AddControllers();

This adds the services needed for controller-based APIs.

Step 3: Database services are registered

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

The application configures how AppDbContext should be provided.

Step 4: Application dependencies are registered

builder.Services.AddScoped<
    IProductRepository,
    ProductRepository>();

builder.Services.AddScoped<
    IProductService,
    ProductService>();

The container learns which implementation fulfills each interface.

Step 5: The application is built

var app = builder.Build();

The application is assembled, including its service provider and request pipeline.

Step 6: An HTTP request arrives

GET /api/products

Routing identifies the relevant controller action.

Step 7: The controller is activated

ASP.NET Core resolves ProductsController and its constructor dependencies.

Step 8: The service is resolved

ProductService receives IProductRepository and ILogger<ProductService>.

Step 9: The repository is resolved

ProductRepository receives AppDbContext.

Step 10: The database is queried

return await _dbContext.Products
    .AsNoTracking()
    .OrderBy(product => product.Name)
    .ToListAsync(cancellationToken);

EF Core executes the database query asynchronously.

Step 11: The result travels back

The repository returns the list to the service. The service returns it to the controller.

Step 12: The HTTP response is created

return Ok(products);

ASP.NET Core serializes the returned data into the response format, normally JSON for this API.

Important distinction: DI supplies the required objects. Routing, EF Core, business logic, and HTTP serialization perform their respective responsibilities.


12. Real Project Usage

Dependency Injection is used across industries because most enterprise applications consist of multiple components that need to collaborate.

IndustryExampleDI benefit
E-commerceProduct, order, payment, and inventory servicesSeparates business logic from storage and external integrations.
BankingAccount services, transaction validation, audit loggingEnables clear component boundaries and testable transaction rules.
HealthcarePatient records, appointment services, notificationsSupports modular services and easier replacement of integrations.
LogisticsShipment tracking, route calculation, delivery notificationsAllows alternative tracking and notification implementations.
Social mediaFeed generation, media storage, messagingSupports different storage providers and independently testable components.
Enterprise softwareReporting, payroll, HR, document managementReduces direct dependencies between business modules.

Example: E-commerce payment processing

An order service should not need to construct a payment gateway directly.

public interface IPaymentService
{
    Task<bool> ProcessPaymentAsync(
        decimal amount,
        CancellationToken cancellationToken);
}

An implementation might use an external payment provider.

public class PaymentService : IPaymentService
{
    public Task<bool> ProcessPaymentAsync(
        decimal amount,
        CancellationToken cancellationToken)
    {
        // Demonstration only.
        // Real payment processing requires a secure provider integration.
        return Task.FromResult(amount > 0);
    }
}

The order service can depend on IPaymentService.

In testing, a fake implementation can simulate successful and failed payments without contacting the real provider.

Production warning: A DI container does not make payment processing secure by itself. Payment verification, authorization, idempotency, secret management, and provider-specific security controls must still be implemented correctly.


13. Performance Considerations

Dependency Injection usually adds little overhead compared with operations such as database access, network calls, and file I/O. Nevertheless, poor service design can affect performance and resource usage.

13.1 Memory

Every object consumes memory.

If services retain large collections or caches unnecessarily, memory consumption can grow.

Avoid:

  • Keeping request-specific data in application-wide objects.
  • Creating unnecessary copies of large objects.
  • Holding references to objects longer than required.
  • Building an unbounded in-memory cache.

Choose a lifetime and ownership model appropriate to the service's data and behavior.

13.2 CPU

The container performs work to resolve dependencies and construct objects.

In a typical web application, this overhead is small. Deep dependency graphs, unnecessary service construction, reflection-heavy custom factories, and repeated manual resolution can add avoidable work.

Keep dependencies focused and avoid constructing expensive objects that are not needed.

13.3 Scalability

A scalable application should not share mutable request-specific state across unrelated requests.

For example, storing the current user's information in a mutable singleton can cause data leakage between requests.

Keep request-specific state within an appropriate request scope or another explicitly managed context.

13.4 Optimization

Recommended practices include:

  • Use asynchronous database and network operations.
  • Avoid unnecessary dependencies in frequently activated components.
  • Keep constructors lightweight.
  • Use caching only when the data and invalidation rules justify it.
  • Avoid resolving the same expensive service repeatedly inside loops.
  • Use AsNoTracking() for suitable read-only EF Core queries.
  • Measure performance before introducing advanced DI optimizations.

Remember: Correct architecture and resource ownership are more important than attempting to optimize DI container resolution prematurely.


14. Security Considerations

Dependency Injection helps organize security-related components, but it does not automatically enforce security policies.

14.1 Accidental data sharing

A singleton that stores user-specific information in mutable fields can expose one user's data to another request.

Prevention: Do not store request-specific state in shared singleton services. Use the correct scope and synchronization strategy.

14.2 Improper secret management

A service may require API keys, database credentials, or other secrets.

Prevention: Obtain secrets from suitable secure configuration providers. Avoid hardcoding credentials in classes or committing them to source control.

14.3 Hidden dependencies

Using IServiceProvider throughout business logic can make it difficult to understand which components a class can access.

Prevention: Prefer explicit constructor injection and register only the dependencies that the application needs.

14.4 Untrusted implementations

If service selection depends on unvalidated user input, an application may accidentally permit inappropriate implementations or unsafe behavior.

Prevention: Control implementation selection through trusted application configuration and explicit business rules.

14.5 Excessive privileges

A service may be constructed with access to resources it does not need.

Prevention: Apply least privilege to database accounts, cloud identities, filesystem access, and external service credentials.

14.6 Shared mutable state

A singleton service may be accessed concurrently by many requests.

Prevention: Prefer stateless implementations or use appropriate thread-safe designs. Do not assume the DI container automatically makes a service thread-safe.


15. Common Mistakes

Mistake 1: Forgetting to register a dependency

Why it happens: A developer creates an interface and implementation but forgets to register them.

Problem: The container cannot resolve the requested service.

Fix:

builder.Services.AddScoped<
    IProductService,
    ProductService>();

Mistake 2: Creating dependencies with new everywhere

Why it happens: Developers are familiar with manually creating objects.

Problem: Consumers become responsible for object construction and may become tightly coupled to implementations.

Fix: Inject required services through constructors and register them centrally.

Manual construction is still appropriate for ordinary objects that do not need container management.

Mistake 3: Assuming every dependency needs an interface

Why it happens: Developers learn that interfaces support loose coupling and apply them to every class.

Problem: Unnecessary abstractions add complexity without a clear benefit.

Fix: Introduce interfaces where they provide meaningful boundaries, substitution, or testing advantages.

Mistake 4: Injecting too many dependencies into one class

Why it happens: A class gradually takes on more responsibilities.

Problem: The class becomes difficult to understand, maintain, and test.

Fix: Review its responsibilities and extract cohesive components where appropriate.

A large constructor is a design signal, not an automatic rule that the class must be split.

Mistake 5: Using IServiceProvider as the default approach

Why it happens: Resolving a service manually appears convenient.

Problem: Dependencies become hidden inside methods.

Fix: Prefer constructor injection unless dynamic resolution is genuinely necessary.

Mistake 6: Confusing DI with Dependency Inversion

Why it happens: Both concepts are often taught together.

Problem: Developers incorrectly assume that using a container automatically produces good architecture.

Fix: Remember that Dependency Inversion is a design principle, whereas DI is a technique for supplying dependencies.

Mistake 7: Assuming registration means immediate construction

Why it happens: Developers interpret service registration as object creation.

Problem: They misunderstand when constructors execute and when initialization happens.

Fix: Distinguish registration from resolution. Many services are created when first requested.

Mistake 8: Ignoring circular dependencies

Why it happens: Two services gradually become dependent on each other.

Problem: The container cannot construct the circular dependency chain normally.

Fix: Refactor responsibilities, introduce an appropriate abstraction, or redesign the workflow so the dependencies no longer form a cycle.

Mistake 9: Storing request data in a singleton

Why it happens: Developers assume that sharing an instance is always efficient.

Problem: Concurrent requests may access shared mutable state, leading to data corruption or cross-request information exposure.

Fix: Keep services stateless where possible and choose lifetimes according to actual ownership and state requirements.

Mistake 10: Testing only through the real database

Why it happens: The application is tested only through integration tests.

Problem: Business logic tests become slow and difficult to isolate.

Fix: Depend on appropriate abstractions and use fakes or mocks when testing business logic independently. Keep integration tests for verifying actual database behavior.


16. Best Practices

Use these practices when designing DI-based applications.

  1. Prefer constructor injection. Make required dependencies explicit.
  2. Depend on abstractions when valuable. Use interfaces where they provide meaningful separation.
  3. Keep constructors simple. Avoid lengthy initialization and unrelated business logic.
  4. Register services in a clear location. Keep the composition root easy to understand.
  5. Separate responsibilities. Avoid putting HTTP, business, and database logic into one class.
  6. Avoid service locator patterns in business logic. Do not hide dependencies behind IServiceProvider.
  7. Choose lifetimes carefully. Consider instance ownership, concurrency, and resource disposal.
  8. Do not capture scoped dependencies in singletons. Follow lifetime rules and validate the container configuration.
  9. Avoid unnecessary abstractions. An interface should have a useful design purpose.
  10. Keep services focused. Each service should have a clear responsibility.
  11. Write unit tests using substitutes. Use fakes or mocks where isolation is appropriate.
  12. Write integration tests. Verify that real registrations and infrastructure work together.
  13. Enable scope validation where appropriate. In development, validate service scopes and dependencies to catch configuration mistakes.
  14. Avoid static service access. Static service locators make dependencies harder to manage and test.
  15. Use asynchronous I/O. Avoid blocking threads during database and network operations.
  16. Avoid shared mutable state. Especially in services reused across requests.
  17. Log meaningful operations. Use ILogger<T> for operational visibility.
  18. Keep secrets outside source code. Use secure configuration providers.
  19. Avoid unnecessary dependencies. Add a service only when a component actually needs it.
  20. Document complex registrations. Explain unusual factory registrations or multiple implementations.
  21. Use meaningful naming. Names such as IOrderService and OrderService communicate purpose.
  22. Do not use DI as a substitute for good design. A poorly structured application can still have DI everywhere.
  23. Avoid circular dependencies. Design clear dependency directions between components.
  24. Validate configuration and registrations. Catch missing dependencies before they cause production failures where practical.
  25. Measure before optimizing. Do not complicate DI configuration without evidence of a performance problem.

17. Interview Questions

Beginner Questions

1. What is Dependency Injection?

Answer: Dependency Injection is a technique in which a class receives its dependencies from an external source rather than creating them itself.

For example, ProductsController receives IProductService through its constructor. This reduces responsibility for object creation and makes the controller easier to test and maintain.

2. Why do we use Dependency Injection in ASP.NET Core?

Answer: We use DI to reduce tight coupling, centralize service registration, simplify testing, and make implementations easier to replace.

ASP.NET Core has a built-in DI container that supplies services to controllers, middleware, and other application components.

3. What is a dependency?

Answer: A dependency is an object or service required by another component.

For example, ProductService may depend on IProductRepository to retrieve product data.

4. What is a DI container?

Answer: A DI container manages registered services and resolves their dependencies when they are requested.

ASP.NET Core's built-in container uses IServiceCollection for registration and IServiceProvider for resolution.

5. What is constructor injection?

Answer: Constructor injection supplies required dependencies through constructor parameters.

public ProductService(IProductRepository repository)
{
    _repository = repository;
}

It makes dependencies explicit and supports testing with substitute implementations.

6. Is an interface mandatory for Dependency Injection?

Answer: No. A concrete class can be registered and injected directly.

Interfaces are useful when an abstraction, multiple implementations, or easier substitution is required.

7. Where do we register services in ASP.NET Core?

Answer: Commonly, we register application services in Program.cs using builder.Services.

builder.Services.AddScoped<
    IProductService,
    ProductService>();

Larger applications can organize registration into extension methods or dedicated registration modules.

8. What happens when a required service is not registered?

Answer: If the container cannot resolve a required dependency, service activation generally fails with an InvalidOperationException.

Register the missing dependency or correct the requested service type.

9. What is tight coupling?

Answer: Tight coupling occurs when a class depends heavily on a specific implementation or its construction details.

Depending directly on SqlProductRepository can make replacement harder than depending on a suitable IProductRepository abstraction.

10. What is the difference between DI and Dependency Inversion?

Answer: Dependency Inversion is a design principle that encourages appropriate dependencies on abstractions. Dependency Injection is a technique for supplying dependencies from outside the consuming class.

DI can help implement Dependency Inversion, but using DI does not automatically guarantee that the architecture follows the principle.

Intermediate Questions

1. Explain the difference between service registration and service resolution.

Answer: Registration describes how a service should be provided. Resolution obtains the requested service instance.

For example, AddScoped<IProductService, ProductService>() registers the mapping. When a controller requests IProductService, the container resolves the registered implementation.

2. Can we inject a concrete class instead of an interface?

Answer: Yes.

builder.Services.AddScoped<ProductService>();

A consumer can request ProductService directly. However, this couples the consumer to that concrete type, which may be acceptable when an abstraction provides no meaningful benefit.

3. What is the difference between constructor injection and method injection?

Answer: Constructor injection supplies dependencies required by the class. Method injection supplies dependencies required by a particular operation.

In ASP.NET Core, [FromServices] can provide a registered service to a controller action parameter.

4. What is the composition root?

Answer: The composition root is the part of the application where dependencies are assembled and configured.

In a typical ASP.NET Core application, Program.cs acts as the composition root because it registers services and builds the application.

5. Can we register multiple implementations of the same interface?

Answer: Yes. The container supports multiple registrations for the same service type.

For example:

builder.Services.AddScoped<IMessageSender, EmailSender>();
builder.Services.AddScoped<IMessageSender, SmsSender>();

A single IMessageSender resolution generally returns the last registration. Resolving IEnumerable<IMessageSender> returns all registered implementations in registration order.

For explicit selection, use a suitable factory, keyed services, or an application-level strategy.

6. What is a circular dependency?

Answer: A circular dependency occurs when services depend on each other directly or indirectly.

For example, OrderService depends on PaymentService, while PaymentService depends on OrderService.

The container cannot construct this circular chain normally. Refactor responsibilities to remove the cycle rather than hiding it through manual service resolution.

7. What is the Service Locator pattern, and why is it often discouraged?

Answer: The Service Locator pattern allows a class to request dependencies from a general-purpose provider instead of declaring them directly.

It is often discouraged in business logic because dependencies become hidden, testing becomes harder, and the class's actual requirements are less visible.

Constructor injection is generally clearer.

8. Does DI automatically make an application thread-safe?

Answer: No. The container creates or supplies instances according to their registrations, but it does not make the code inside those instances thread-safe.

Developers must account for shared mutable state, concurrent requests, synchronization, and the thread-safety guarantees of underlying resources.

9. How does DI help unit testing?

Answer: DI allows a test to supply a fake or mock implementation instead of using the production dependency.

A test can replace a real database repository with an in-memory fake and test business logic without requiring a database.

10. What is the relationship between DI and SOLID?

Answer: DI commonly supports the Dependency Inversion Principle and can help classes remain focused on their responsibilities. However, it does not automatically enforce all SOLID principles.

Good naming, cohesive responsibilities, meaningful abstractions, and appropriate dependency direction are still necessary.

Advanced Questions

1. How does the built-in DI container resolve nested dependencies?

Answer: The container inspects the requested type's constructor, identifies its parameters, and attempts to resolve those parameter types using registrations and supported framework services.

It recursively resolves the dependency graph and constructs the requested object when possible.

If a required dependency cannot be resolved, or a circular dependency prevents construction, resolution fails.

2. What happens when a constructor has multiple resolvable parameters?

Answer: The default container generally selects the applicable public constructor with the most parameters it can resolve, subject to its constructor-selection rules.

Ambiguous constructor configurations can cause resolution failures.

Keep constructors unambiguous and ensure the intended dependencies are clear.

3. Why is injecting IServiceProvider into every service a design problem?

Answer: It hides dependencies that would otherwise be visible in the constructor.

This can make unit testing harder and shift dependency resolution into application logic.

Use it when dynamic resolution is genuinely needed, not as a replacement for ordinary constructor injection.

4. What are captive dependencies?

Answer: A captive dependency occurs when a longer-lived service holds a reference to a shorter-lived service beyond the intended lifetime of that dependency.

For example, a singleton holding a scoped service can cause scope-related correctness problems.

Avoid capturing scoped services in singletons. When background work genuinely needs scoped services, create an explicit scope with IServiceScopeFactory.

5. How can DI registration errors be caught earlier?

Answer: Use service-provider validation and scope validation in development and testing where appropriate.

builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes = true;
    options.ValidateOnBuild = true;
});

These checks help identify certain invalid dependency graphs and scope misuse. They do not guarantee that every runtime resolution problem will be detected at startup.

6. What is the difference between the DI container and a service factory?

Answer: A DI container resolves registered services and their dependency graphs. A factory encapsulates the logic for creating or selecting a particular object.

Factories can be registered with the container, allowing custom creation logic while keeping construction responsibility outside the consumer.

7. When might a factory registration be appropriate?

Answer: A factory can be useful when constructing a service requires custom initialization, selecting among trusted implementations, or adapting configuration into an object.

However, ordinary services should generally use straightforward constructor injection. Avoid using factories to hide complex dependency graphs.

8. How should dependencies be handled in background services?

Answer: A hosted service is commonly registered as a singleton. It should not directly capture a scoped service such as a typical EF Core DbContext.

Instead, inject IServiceScopeFactory, create a scope for the work unit, resolve the scoped service inside that scope, and dispose of the scope when the work finishes.

9. How does DI relate to the Open/Closed Principle?

Answer: DI can make it easier to introduce new implementations behind existing abstractions without modifying consumers.

However, the Open/Closed Principle also depends on how the abstraction is designed. A poor interface can still force frequent changes to existing code.

10. When would you choose a third-party DI container?

Answer: ASP.NET Core's built-in container handles most common application requirements.

A third-party container may be justified when a project needs advanced features that the built-in container does not provide conveniently, such as particular convention-based registrations or specialized resolution capabilities.

The choice should be based on concrete requirements, operational complexity, team familiarity, and maintenance costs—not simply because a larger container has more features.


18. Hands-on Exercise

Exercise: Build a Notification API using Dependency Injection

Objective: Create a simple ASP.NET Core API that uses an interface, a service implementation, and constructor injection.

Requirements

  1. Create an interface named INotificationService.
  2. Add a method named SendNotification().
  3. Create a class named NotificationService that implements the interface.
  4. Register the service in Program.cs.
  5. Inject it into NotificationsController.
  6. Create a GET /api/notifications endpoint.
  7. Return the message from the notification service.

Expected response

"Notification sent successfully."

Bonus challenge

Create a second implementation named EmailNotificationService.

Register the implementation you want to use and confirm that the controller does not need to change.

Then write a unit test using a fake implementation of INotificationService.

Completion criteria

  • The API runs successfully.
  • The controller does not construct the service with new.
  • The dependency is registered correctly.
  • The controller depends on the interface.
  • You can replace the implementation without changing the controller.

19. Mini Project: Order Processing API

Project objective

Build a small order-processing API that demonstrates Dependency Injection across multiple application layers.

Features

  • Create an order.
  • Retrieve an order by ID.
  • Calculate the total price.
  • Validate the requested items.
  • Simulate payment processing.
  • Log order processing events.

Recommended abstractions

IOrderService
IOrderRepository
IPaymentService
IOrderValidator

Example dependency structure

Suggested implementation stages

Stage 1: Models

Create Order and OrderItem models.

Stage 2: Interfaces

Define the repository, payment, validation, and order service contracts.

Stage 3: Implementations

Create in-memory implementations for the first version.

Stage 4: Registration

Register the implementations in Program.cs.

Stage 5: Controller

Inject IOrderService into OrdersController.

Stage 6: Testing

Use fake implementations to test successful and unsuccessful order processing.

Stage 7: Improvement

Replace the in-memory repository with EF Core without changing the controller's contract.

What you should learn

This project demonstrates how DI supports modular design, testing, replacement of implementations, and separation of responsibilities.

The payment service should remain a simulation until you implement a proper payment provider integration with secure configuration, authorization, and idempotency.


20. Quiz

Question 1

What is the primary purpose of Dependency Injection?

A. To replace C# interfaces.

B. To make classes receive their dependencies from outside rather than creating them internally.

C. To eliminate all object creation.

D. To replace the ASP.NET Core request pipeline.

Correct answer: B

Explanation: DI transfers responsibility for supplying dependencies away from the consuming class. Objects are still created; their construction is managed by the appropriate external mechanism.

Question 2

Where are services commonly registered in a basic ASP.NET Core application?

A. appsettings.json

B. ProductsController

C. Program.cs

D. The HTML view.

Correct answer: C

Explanation: Program.cs is the common place to configure builder.Services, although registrations can also be organized into extension methods and other modules.

Question 3

Which technique is generally preferred for required dependencies?

A. Constructor injection.

B. Static global variables.

C. Repeated calls to new.

D. Hidden service locator calls.

Correct answer: A

Explanation: Constructor injection makes requirements explicit and helps prevent a class from being created without its required dependencies.

Question 4

Is an interface mandatory for DI?

A. Yes, for every service.

B. Yes, but only in controllers.

C. No, concrete classes can also be injected.

D. No, because DI works only with static classes.

Correct answer: C

Explanation: The container can register concrete classes directly. Interfaces are useful where abstractions and implementation substitution provide value.

Question 5

What happens when the container cannot resolve a required service?

A. It always returns null.

B. It silently skips the dependency.

C. It creates a random implementation.

D. Resolution generally fails with an exception.

Correct answer: D

Explanation: The built-in container throws an exception when a required dependency cannot be resolved. Correct the registration or dependency graph.

Question 6

What is Dependency Inversion?

A. A technique that converts interfaces into abstract classes.

B. A principle that encourages appropriate dependence on abstractions rather than concrete details.

C. A method for registering every class as a singleton.

D. A database optimization technique.

Correct answer: B

Explanation: Dependency Inversion is a design principle. DI is a technique that can help implement it.

Question 7

Which statement about IServiceProvider is correct?

A. It can never be used in ASP.NET Core.

B. It is the same as an interface implementation.

C. It provides access to services registered with the container.

D. It automatically makes every service thread-safe.

Correct answer: C

Explanation: IServiceProvider is used to resolve services. Using it extensively in business logic can hide dependencies, and it does not guarantee thread safety.

Question 8

What is a circular dependency?

A. A service that depends directly or indirectly on itself through other services.

B. A service that uses an interface.

C. A service registered with a scoped lifetime.

D. A service that logs a database query.

Correct answer: A

Explanation: A dependency cycle prevents the container from constructing the graph normally. The usual solution is to refactor the responsibilities and dependency direction.

Question 9

Does DI automatically make an application secure?

A. Yes, always.

B. Yes, if every service has an interface.

C. Yes, if every service is scoped.

D. No, security still depends on application design and implementation.

Correct answer: D

Explanation: DI organizes dependencies. Authentication, authorization, secret management, input validation, and safe state management still require explicit implementation.

Question 10

Why is DI helpful for unit testing?

A. It removes the need for assertions.

B. It allows test implementations to replace real dependencies.

C. It makes every database query run in memory.

D. It guarantees that every test passes.

Correct answer: B

Explanation: A fake or mock dependency allows the test to isolate the class under test and simulate different scenarios without invoking the real external system.


21. Summary

One-minute revision

Dependency Injection is a technique in which a class receives the objects it needs rather than creating them itself.

ASP.NET Core provides a built-in DI container. Developers register services through builder.Services, and the framework resolves registered dependencies when components need them.

Constructor injection is the preferred default for required dependencies. DI can reduce coupling, improve testability, and make implementations easier to replace.

DI and Dependency Inversion are related but different. DI does not automatically guarantee good architecture, thread safety, or security.

Five-minute revision

Remember the complete workflow:

  1. Define an interface when an abstraction provides value.
  2. Implement the interface in a concrete class.
  3. Register the mapping in Program.cs.
  4. Request the dependency through a constructor.
  5. Let ASP.NET Core resolve the service.
  6. Use the service through its declared contract.
  7. Substitute a fake or alternative implementation when testing or changing infrastructure.

Example:

public interface IProductService
{
    string GetProductName();
}

public class ProductService : IProductService
{
    public string GetProductName() => "Laptop";
}

Register it:

builder.Services.AddScoped<
    IProductService,
    ProductService>();

Inject it:

public class ProductsController : ControllerBase
{
    private readonly IProductService _service;

    public ProductsController(IProductService service)
    {
        _service = service;
    }
}

Bullet-point summary

  • DI separates dependency creation from dependency usage.
  • ASP.NET Core has a built-in DI container.
  • IServiceCollection is used to register services.
  • IServiceProvider resolves registered services.
  • Constructor injection makes required dependencies explicit.
  • Interfaces support abstraction but are not mandatory for DI.
  • DI improves testability when consumers depend on replaceable components.
  • Dependency Inversion is a principle, not a container feature.
  • Circular dependencies and invalid lifetime relationships can cause problems.
  • A DI container does not automatically guarantee thread safety or security.

Memory tricks

DI = Declare → Register → Resolve → Use

  • Declare: Define what the class needs.
  • Register: Tell the container how to provide it.
  • Resolve: Let the container supply the dependency.
  • Use: Call the service through its contract.

Remember this distinction:

  • DI: How dependencies are supplied.
  • Dependency Inversion: How dependencies should be structured.
  • DI container: The mechanism that resolves registered dependencies.

Flashcards

QuestionAnswer
What is DI?Supplying dependencies from outside the consuming class.
What is a dependency?An object required by another component.
What is constructor injection?Passing required dependencies through constructor parameters.
Where are services commonly registered?Program.cs, using builder.Services.
What is the DI container?The mechanism that resolves registered services.
Is an interface mandatory?No.
What is Dependency Inversion?A principle encouraging suitable dependencies on abstractions.
What is a circular dependency?A cycle in the dependency graph.
Does DI make services thread-safe?No.
What is the next topic?Service Lifetime.

22. Cheat Sheet

Essential syntax

Register an interface and implementation

builder.Services.AddScoped<
    IProductService,
    ProductService>();

Register a concrete service

builder.Services.AddScoped<ProductService>();

Inject a dependency

public class ProductService
{
    private readonly IProductRepository _repository;

    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
}

Inject a framework-provided logger

public class ProductService
{
    private readonly ILogger<ProductService> _logger;

    public ProductService(ILogger<ProductService> logger)
    {
        _logger = logger;
    }
}

Important methods

MethodPurpose
AddTransient<TService, TImplementation>()Register a transient service.
AddScoped<TService, TImplementation>()Register a scoped service.
AddSingleton<TService, TImplementation>()Register a singleton service.
AddDbContext<TContext>()Configure an EF Core context registration.
GetRequiredService<T>()Resolve a service or throw if it cannot be resolved.
GetServices<T>()Resolve all registered services of a type through the provider extensions.

Interview reminders

  • DI is not the same as Dependency Inversion.
  • An interface is useful but not mandatory.
  • Constructor injection is the preferred default.
  • Registration and construction are separate operations.
  • Multiple registrations can be resolved as IEnumerable<T>.
  • Avoid circular dependencies and hidden service resolution.
  • A singleton is not automatically thread-safe.
  • Understand service lifetimes before designing long-running or request-based services.

23. Comparison Table

Dependency Injection vs Dependency Inversion

Dependency InjectionDependency Inversion
A technique for supplying dependencies.A design principle governing dependency direction.
Often implemented with a DI container.Can be followed without a DI container.
Focuses on how objects receive dependencies.Focuses on how components depend on abstractions.
Example: Inject IProductRepository into a service.Example: Business logic depends on a repository abstraction instead of SQL-specific details.

DI vs Service Locator

Dependency InjectionService Locator
Dependencies are explicitly declared.Dependencies are requested from a provider.
Constructor injection makes requirements visible.Requirements can be hidden inside methods.
Usually easier to test and understand.Can make testing and dependency analysis more difficult.
Preferred for ordinary application services.Useful only for specific cases where dynamic resolution is justified.

Constructor Injection vs Method Injection

Constructor injectionMethod injection
Dependencies are supplied during construction.Dependencies are supplied to an individual method.
Best for required dependencies.Useful when only a particular operation needs the dependency.
Requirements are visible at the class boundary.Requirements are visible at the method boundary.
Commonly used in controllers and services.Commonly used with action parameters and [FromServices].

DI vs Manual Object Creation

Dependency InjectionManual object creation
A class receives its dependency from outside.A class creates the dependency itself.
Makes substitution and testing easier when designed appropriately.Can tightly couple consumers to concrete implementations.
Construction can be centralized.Construction logic can become duplicated.
Best suited to application-managed dependencies.Still appropriate for simple objects and local value construction.

24. Key Takeaways

  1. Dependency Injection is a core architectural technique in modern ASP.NET Core applications.
  2. It separates dependency creation from dependency usage.
  3. ASP.NET Core's built-in container handles registration and resolution.
  4. Constructor injection makes dependencies explicit and testable.
  5. Interfaces provide useful abstraction but are not required for every service.
  6. DI supports Dependency Inversion but does not guarantee it.
  7. The container manages registered services according to their configurations; developers remain responsible for good design.
  8. Correct lifetime selection, concurrency handling, secret management, and security remain essential.
  9. Unit tests can substitute dependencies, while integration tests verify the real dependency graph.
  10. Understanding DI is the foundation for understanding Service Lifetime, the next roadmap module.

25. Revision Checklist

Use this checklist before moving to the next topic.

  • I can explain Dependency Injection in my own words.
  • I understand the difference between a dependency and a consumer.
  • I can explain tight coupling and loose coupling.
  • I understand why interfaces can help decouple components.
  • I can register a service in Program.cs.
  • I can inject a service through a constructor.
  • I understand how the container resolves nested dependencies.
  • I can explain registration versus resolution.
  • I know when method injection may be useful.
  • I understand DI versus Dependency Inversion.
  • I can identify a missing registration.
  • I know why circular dependencies are problematic.
  • I can explain why service locator usage should be limited.
  • I understand how DI supports unit testing.
  • I know that DI does not automatically guarantee security or thread safety.
  • I understand the basic purpose of service lifetimes.
  • I can complete the notification API exercise.

26. Further Reading

Continue learning through these related Logic Lense Roadmaps modules:

  1. Generic Host — Understand how ASP.NET Core configures hosting, application startup, configuration, and services.
  2. Service Lifetime — Learn the differences between Transient, Scoped, and Singleton registrations, including object reuse, disposal, and lifetime-related errors.
  3. Configuration and appsettings.json — Learn how to manage application settings through configuration providers.
  4. Options Pattern — Learn how to bind configuration sections to strongly typed settings classes.
  5. Middleware in ASP.NET Core — Understand how requests flow through the middleware pipeline.
  6. Logging in ASP.NET Core — Learn how to use ILogger<T> for structured application logging.
  7. Entity Framework Core — Understand database contexts, entity tracking, and database access.
  8. Unit Testing in .NET — Learn how to isolate services and test business logic using fakes and mocks.

Last updated 10/13/2026

Your notes

Sign in to save personal notes on this topic — they'll sync across your devices.

Was this tutorial helpful?

Help us create more free learning resources. Learn more

Make a Donation