From 26cab4819b17468ba0ef13356a6700298d235108 Mon Sep 17 00:00:00 2001 From: Swiftly1 <77643169+Swiftly1@users.noreply.github.com> Date: Tue, 23 Nov 2021 10:49:17 +0100 Subject: [PATCH] [Minimal API docs] Adding an example of how to resolve dependencies just like in configure method (#23998) Co-authored-by: Kirk Larkin <6025110+serpent5@users.noreply.github.com> --- aspnetcore/fundamentals/minimal-apis.md | 8 +++++++ .../samples/WebMinAPIs/Program.cs | 23 ++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/aspnetcore/fundamentals/minimal-apis.md b/aspnetcore/fundamentals/minimal-apis.md index c6a6830c44..bf8ddbb381 100644 --- a/aspnetcore/fundamentals/minimal-apis.md +++ b/aspnetcore/fundamentals/minimal-apis.md @@ -147,6 +147,14 @@ The following code writes a message to the log on application startup: For more information, see +### Access the Dependency Injection (DI) container + +The following code shows how to get services from the DI container during application startup: + +[!code-csharp[](minimal-apis/samples/WebMinAPIs/Program.cs?name=snippet_dependencies)] + +For more information, see . + ## WebApplicationBuilder This section contains sample code using . diff --git a/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs b/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs index a01eee8c16..73679f9b40 100644 --- a/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs +++ b/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs @@ -1,4 +1,4 @@ -#define Default // Default CREATE P1 PM PE I1 I0 IP CERT CERT2 CERT3 RE CONFIG LOG REB +#define Default // Default CREATE P1 PM PE I1 I0 IP CERT CERT2 CERT3 RE CONFIG LOG #i REB // CONFIGB LOGB IWHB DEP R1 LE LF IM SM NR NR2 RP WILD CON OV EPB OP1 OP2 OP3 OP4 // CB BA CJSON MULTI STREAM XTN AUTH1 AUTH2 AUTH3 AUTH4 CORS CORS2 SWAG SWAG2 // FIL2 IHB CHNGR ADDMID @@ -207,6 +207,27 @@ app.MapGet("/", () => "Hello World"); app.Run(); #endregion +#elif DEPS +#region snippet_dependencies + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddControllers(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +app.MapControllers(); + +using (var scope = app.Services.CreateScope()) +{ + var sampleService = scope.ServiceProvider.GetRequiredService(); + sampleService.DoSomething(); +} + +app.Run(); +#endregion +class SampleService { public void DoSomething() { } } #elif REB // Read Env Builder #region snippet_reb var builder = WebApplication.CreateBuilder(args);