- Home
- .NET coding challenges
- Adding services to dependency injection in ASP.NET Core
Adding services to dependency injection in ASP.NET Core
Adding services to dependency injection in ASP.NET Core application can be done in the Program.cs
file.
Services can be configured with either the singleton, scoped or transient service lifetime. You can find out more about the different service lifetimes by watching our video.
We have this service that we wish to add to the IoC container:
public interface IVehicleService {
}
public class VehicleService : IVehicleService {
}
There is a VehicleService
class that inherits the IVehicleService
interface.
Here is the Program.cs
file in our ASP.NET Core app.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
How would you add this service with a scoped service lifetime to the configuration in Program.cs
? The IVehicleService
interface would be the service and the VehicleService
class would be the implementation.
Give us your anonymous feedback regarding this page, or any other areas of the website.