15 Mar 2024
In ASP.NET Core framework, IServiceCollection
is an interface provided by the framework within the dependency injection system. It serves as a container for registering application services during the startup configuration phase. It provides methods for adding services to the container, configuring services, and specifying their lifetimes.
Common methods provided by IServiceCollection
are:
-
AddTransient<TService, TImplementation>()
: Registers a transient service with its implementation type. Transient services are created each time they are requested. -
AddScoped<TService, TImplementation>()
: Registers a scoped service with its implementation type. Scoped services are created once per request within the scope. -
AddSingleton<TService, TImplementation>()
: Registers a singleton service with its implementation type. Singleton services are created only once and shared throughout the application lifetime. -
AddTransient<TService>()
,AddScoped<TService>()
,AddSingleton<TService>()
: These methods can also be used to register services without explicitly specifying their implementation types. In such cases, the container is responsible for resolving the implementation types based on conventions or explicit configuration.
Key Points of IServiceCollection
:
-
Service Registration:
IServiceCollection
is used to register the services that your application depends on. These services could be anything from database contexts, repositories, to custom services that perform specific tasks in your application. -
Dependency Injection: Once services are registered with
IServiceCollection
, ASP.NET Core's built-in dependency injection system uses this collection to manage the instantiation and lifetime of these services. Dependency injection allows your application components to be loosely coupled, making it easier to maintain, test, and extend your codebase. -
Configuration:
IServiceCollection
provides methods to register services with different lifetimes such asAddSingleton
,AddTransient
, andAddScoped
, allowing you to control how instances of services are created and managed throughout the application's lifecycle. -
Extensibility: It's extensible, meaning you can also add third-party services and configure them within the
IServiceCollection
, enabling you to integrate various libraries and frameworks seamlessly into your ASP.NET Core application.
In simple terms, IServiceCollection
is like a catalog where you list all the services your application needs. ASP.NET Core then uses this catalog to ensure that these services are available to be injected wherever they are needed throughout your application.
Example:
In ASP.NET Core, IServiceCollection
is used for configuring and defining application services, which are then consumed by the application through dependency injection. Here's an example of how you might use IServiceCollection
in an ASP.NET Core WebAPI project:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using YourNamespace.Services; // Assuming you have some services to inject
namespace YourNamespace
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add Authorization
services.AddAuthorization();
// Add SwaggerGen
services.AddSwaggerGen();
// Add Caching
services.AddMemoryCache();
// Add Options
services.Configure<SomeOptions>(Configuration.GetSection("SomeOptions"));
services.AddControllers();
// Example of registering a custom service
services.AddScoped<IMyScopedService, MyScopedService>();
services.AddTransient<IMyTransientService, MyTransientService>();
services.AddSingleton<IMySingletonService, MySingletonService>();
// You can register other services like DbContext, HttpClient, etc.
services.AddDbContext<MyDbContext>();
services.AddHttpClient<IMyHttpClient, MyHttpClient>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// In production, you might want to use more specific error handling middleware
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
In this example:
-
In the
ConfigureServices
method, services are registered with theIServiceCollection
.AddScoped
,AddTransient
, andAddSingleton
are different lifetime options for services. Here,AddScoped
is used for registering a service that has a scoped lifetime. -
AddControllers
is used to add controllers to the service collection. -
AddDbContext
,AddHttpClient
, etc., can be used to register other types of services like Entity Framework Core contexts, HTTP clients, etc. -
In the
Configure
method, you configure the HTTP request pipeline. Here, middleware for handling exceptions, HTTPS redirection, routing, authorization, and endpoint mapping is added.
This is a basic example, but IServiceCollection
is quite flexible, allowing for the registration of a wide variety of services that your application might need.