DI in .Net Core

Transient

Transient objects are always different; a new instance is provided to every controller and every service.

1
2
3
4
5
services.AddTransient<IOssIndexRepository, OssIndexRepository>();

// with parameters
var projectRepository = new ProjectRepository(connectionString);
services.AddTransient<IProjectRepository>(s => projectRepository);

Scoped

Scoped objects are the same within a request, but different across different requests.

1
services.AddScoped<IOperationScoped, Operation>();

Singleton

Singleton objects are the same for every object and every request.

1
2
var ossIndexRepository = new OssIndexRepository(connectionString);
services.AddSingleton<IOssIndexRepository>(ossIndexRepository);

References