You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: aspnetcore/mvc/controllers/dependency-injection.md
+10-10Lines changed: 10 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,7 +3,7 @@ title: Dependency injection into controllers in ASP.NET Core
3
3
author: ardalis
4
4
description: Discover how ASP.NET Core MVC controllers request their dependencies explicitly via their constructors with dependency injection in ASP.NET Core.
5
5
ms.author: riande
6
-
ms.date: 10/12/2022
6
+
ms.date: 10/13/2022
7
7
uid: mvc/controllers/dependency-injection
8
8
---
9
9
# Dependency injection into controllers in ASP.NET Core
@@ -21,49 +21,49 @@ ASP.NET Core MVC controllers request dependencies explicitly via constructors. A
21
21
22
22
Services are added as a constructor parameter, and the runtime resolves the service from the service container. Services are typically defined using interfaces. For example, consider an app that requires the current time. The following interface exposes the `IDateTime` service:
For more information on <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton*>, see [DI service lifetimes](xref:fundamentals/dependency-injection#service-lifetimes).
35
35
36
36
The following code displays a greeting to the user based on the time of day:
Run the app and a message is displayed based on the time.
41
41
42
42
## Action injection with `FromServices`
43
43
44
44
The <xref:Microsoft.AspNetCore.Mvc.FromServicesAttribute> enables injecting a service directly into an action method without using constructor injection:
Accessing app or configuration settings from within a controller is a common pattern. The *options pattern* described in <xref:fundamentals/configuration/options> is the preferred approach to manage settings. Generally, don't directly inject <xref:Microsoft.Extensions.Configuration.IConfiguration> into a controller.
51
51
52
52
Create a class that represents the options. For example:
0 commit comments