-
Notifications
You must be signed in to change notification settings - Fork 0
Dependency Injection
Shady Ashraf Abdelhameed edited this page Jan 31, 2025
·
1 revision
Dependency Injection and DbContext in ASP.NET Core
- 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.csfile.
- 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.
- A class (e.g.,
- 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.
- The dependency (e.g.,
Steps to Inject DbContext in ASP.NET Core
-
Open
Program.cs. -
Register the
DbContextClass:builder.Services.AddDbContext<TRWalksDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("TRWalksConnectionString")));-
AddDbContext: Adds theDbContextto the DI container. -
UseSqlServer: Configures Entity Framework Core to use SQL Server. -
Connection String: Retrieved from
appsettings.jsonusingbuilder.Configuration.GetConnectionString.
-
-
Configure Connection String in
appsettings.json:"ConnectionStrings": { "TRWalksConnectionString": "Server=<YourServerName>;Database=TRWalksDB;Trusted_Connection=True;TrustServerCertificate=True;" } -
Verify DI Registration:
- Once registered, the
DbContextcan be injected into controllers or repositories.
- Once registered, the
- The
DbContextis 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.