Skip to content

Dependency Injection

Shady Ashraf Abdelhameed edited this page Jan 31, 2025 · 1 revision

Dependency Injection and DbContext in ASP.NET Core

**What is Dependency Injection (DI)?

  • Definition: A design pattern that reduces coupling between components, increasing maintainability and testability.
  • Core Principle: Instead of instantiating objects directly in a class, they are passed as parameters to constructors or methods.
  • Benefits:
    • Flexible object creation and management.
    • Simplifies testing of individual components.
    • Enables adherence to SOLID principles (e.g., the Dependency Inversion principle).

DI in ASP.NET Core

  • ASP.NET Core has a built-in dependency injection container.
  • The container manages the lifetime and dependencies of services registered during application startup.
  • Services can be registered in the Program.cs file.

Non-DI Example

  • In a non-DI scenario:
    • A class (e.g., MyController) directly instantiates a dependency (e.g., MyService).
    • Any changes to MyService (e.g., renaming or replacing it) require modifying all the consuming classes.

DI Example

  • In a DI scenario:
    • The dependency (e.g., MyService) is injected into the consumer (e.g., MyController) via the constructor or a method.
    • The implementation of the dependency is defined in one place (Program.cs), making it easier to manage changes.

Steps to Inject DbContext in ASP.NET Core

  1. Open Program.cs.

  2. Register the DbContext Class:

    builder.Services.AddDbContext<TRWalksDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("TRWalksConnectionString")));
    
    
    • AddDbContext: Adds the DbContext to the DI container.
    • UseSqlServer: Configures Entity Framework Core to use SQL Server.
    • Connection String: Retrieved from appsettings.json using builder.Configuration.GetConnectionString.
  3. Configure Connection String in appsettings.json:

    "ConnectionStrings": {
      "TRWalksConnectionString": "Server=<YourServerName>;Database=TRWalksDB;Trusted_Connection=True;TrustServerCertificate=True;"
    }
    
    
  4. Verify DI Registration:

    • Once registered, the DbContext can be injected into controllers or repositories.

Outcome

  • The DbContext is managed by ASP.NET Core's DI container.
  • It can be used throughout the application in controllers or repositories without manual instantiation.
  • Simplifies database interaction and enables flexibility for changes.

Clone this wiki locally