ServiceCollection
Microsoft.Extensions.DependencyInjection
Summary
ClassRepresents a collection of service descriptors that can be used to register services with a dependency injection container.
This class implements IServiceCollection
and provides the functionality to add, remove, and manage service registrations.
Members
Constructors
Name | Description |
---|---|
ServiceCollection() | Initializes a new instance of the ServiceCollection class. |
Methods
Name | Description |
---|---|
Add(ServiceDescriptor) | Adds the specified ServiceDescriptor to the collection. |
AddSingleton() | Adds a singleton service of the specified type to the collection. |
AddSingleton<TService>() | Adds a singleton service of the specified type to the collection. |
AddScoped<TService>() | Adds a scoped service of the specified type to the collection. |
AddTransient<TService>() | Adds a transient service of the specified type to the collection. |
BuildServiceProvider() | Builds an IServiceProvider from the current service descriptors. |
Properties
Name | Type | Description |
---|---|---|
Count | int | Gets the number of elements contained in the ServiceCollection . |
IsReadOnly | bool | Gets a value indicating whether the ServiceCollection is read-only. |
Example Usage
var services = new ServiceCollection(); // Add a singleton service services.AddSingleton<IMyService, MyServiceImplementation>(); // Add a scoped service services.AddScoped<IOtherService>(); // Add a transient service services.AddTransient<ILoggerFactory>(); // Build the service provider using (var provider = services.BuildServiceProvider()) { // Resolve services from the provider var myService = provider.GetService<IMyService>(); }