Wednesday, December 21, 2022

.Net Dependency Injection

.Net Dependency Injection Service Lifetimes:


Transient

Transient lifetime services are created each time they are requested.

Example:

services.AddTransient<IRequest, MyAppRequest>();


Scoped

For web applications, a Scoped lifetime indicates that services are created once per client connection.

Example:

services.AddScoped<ISettings, ClientSettings>();


Singleton

Singleton lifetime services are created the first time they are requested.  

Accessing application configuration or loading static data are examples of when to use Singleton service.

Example:

services.AddSingleton<ISettings, MyAppSettings>();


Extension Methods:

AddBlobServiceClient

Add Azure Blob Storage

Example:


AddDbContext

A Scoped lifetime service used with Entity Framework Core to connect to a database.

Example:

services.AddDbContext<DataContext>(options => options.UseSqlServer("name=ConnectionStrings:SQLConnectionString"), ServiceLifetime.Scoped);


AddOptions

Extension method for adding configuration related options services to the DI container

Example:


AddQueueServiceClient

Azure Queue Service Client. 

Example:


AddSecretClient

Azure Key Vault Secrets

Example:


AddSqlServer

Registers the given Entity Framework DbContext as a service in the IServiceCollection and configures it to connect to a SQL Server database.

Example:

services.AddSqlServer<DataContext>(hostContext.Configuration["ConnectionStrings:SQLConnectionString"]);