The
IServiceCollection
interface is defined in the
Microsoft.Extensions.DependencyInjection
namespace. It’s used within the
dependency injection
mechanism for .NET to hold all registered services accessible to a service container that implements
IServiceProvider
.
IServiceCollection
implements both the
ICollection<T>
interface, which grants it methods to manipulate generic collections, and, the
IEnumerable
interface, which allows code to iterate over its contents. An instance of a class that implements the IServiceCollection
interface provides its services to objects that have access to the instance. As an example, we can take a look at the
Services
property of the
WebApplicationBuilder
class:
public Microsoft.Extensions.DependencyInjection.IServiceCollection Services { get; }
In a default ASP.NET (v8.0) app, an instance of the WebApplicationBuilder
is created in the Program.cs class:
var builder = WebApplication.CreateBuilder(args);
Services can then be added to the builder.Services
collection via
its numerous extension methods
.
In the example below, we add a database context service via the
AddDbContext
method of the EntityFrameworkServiceCollectionExtensions
class
// builder.Services is the IServiceCollection of the application builder
builder.Services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("todo"));
We can then access the database context service via a controller:
[Route("api/[controller]")]
public class TodoController : ControllerBase {
private readonly TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Todo>>> GetTodos()
{
return await _context.Todos.ToListAsync();
}
}