Dependency injection

Each service should have an abstraction (interface)

here are three service lifetimes in ASP.NET Core Dependency Injection:

  • Transient services are created every time they are injected or requested.
  • Scoped services are created per scope. In a web application, every web request creates a new separated service scope. That means scoped services are generally created per web request.
  • Singleton services are created per DI container. That generally means that they are created only one time per application and then used for whole the application life time.

Example to register services for dependency injection

services.AddScoped<IBookService, BookService>();

Split services registrations:

https://fmoralesdev.com/2019/09/20/extension-method-to-split-services-registrations-dependency-injection-net-core-part-iii/

https://stackoverflow.com/questions/48772049/how-can-i-split-up-my-service-registations-into-different-files-in-asp-net-core

Example to register DbContext for dependency injection

https://stackoverflow.com/questions/48443567/adddbcontext-or-adddbcontextpool

var connectionString = _configuration.GetConnectionString("MySqlDatabase");
services.AddDbContext<DatabaseContext>(options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

References

results matching ""

    No results matching ""