Basic programming, .NET technology.

2 - [Updated] - ASP .Net core - Fundamentals - Dependency injection

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file in ASP .Net core.

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.


    In this note, I want to summary some knowledge about DI in Asp.net core.



First, DI is to archive Inversion of Control, solid principle.
We have 3 types of DI: constructor injection, method injection, property injection

The built-in DI of the .net core base on constructor injection.

a. How to register services
  • Register a service in method 'ConfigureServices'
  • Use the "services.Configure" method to config/binding  our configuration to option
  • also can create an extension method of IServicesCollection to compute a group of related service
    • Note: convention : Add{OurServiceName}, for example: AddDataAcessLayer, AddBusinessServices...

b. Service lifetime
  • Transient: short lifetime, create when  service container request, disposed at the end of the request
  • Scoped: create per client request, AddDbContext for example.
  • Singleton: create at the first time that they're requested; disposed of an object only when app shutdown, should consider if we use it, since memory performance

c. Design service for dependency injection
When designing services for dependency injection:
  • Avoid stateful, static classes and members. Avoid creating a global state by designing apps to use singleton services instead.
  • Avoid use Service Locator anti-pattern.
  • Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
  • Make services small, well-factored, and easily tested.
d. Dispose of services: Container takes this responsibility

e. Keyed Service (From ASP.NET Core 8)
When using keyed services:
  • Have an interface with multiple implementations
  • And need to use one of those implementations in different places in your application
Add services by using: AddKeyedSingleton (or AddKeyedScoped or AddKeyedTransient)

builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");

Access a registered service by specifying the key with the [FromKeyedServices]

[HttpGet("big-cache")]
public ActionResult<object> GetOk([FromKeyedServices("big")] ICache cache)
{
    return cache.Get("data-mvc");
}


Ref:
Share:

0 nhận xét:

Đăng nhận xét

Featured Posts

Data type 3 - string type