Dependency Injection of a Type within Program.cs Using Top Level Statements
Full source code available here.
This is a follow-up post to one I wrote yesterday. In that I showed how to add an instance of an Entity Framework Context to the service collection, then use the context later in Program.cs
to create and seed the database.
Today I will show the more general case for this example, adding a simple type to the service collection, and using it later in Program.cs
.
1using DIWithinProgram;
2
3var builder = WebApplication.CreateBuilder(args);
4
5builder.Services.AddControllers();
6builder.Services.AddScoped<ISomeService, SomeService>();
7
8var app = builder.Build();
9
10int result = 0;
11using (var scope = app.Services.CreateScope())
12{
13 var someService = scope.ServiceProvider.GetRequiredService<ISomeService>();
14 result = someService.Add(2, 3);
15}
16app.MapGet("/", () => result);
17
18app.MapControllers();
19
20app.Run();
For completeness, here is the service and its interface:
1namespace DIWithinProgram;
2
3public class SomeService : ISomeService
4{
5 public int Add(int num1, int num2)
6 {
7 return num1 + num2;
8 }
9}
10
11public interface ISomeService
12{
13 int Add(int num1, int num2);
14}
Full source code available here.