Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
By Shadi Alnamrouti and Rick Anderson
ASP.NET Core MVC controllers request dependencies explicitly via constructors. ASP.NET Core has built-in support for dependency injection (DI). DI makes apps easier to test and maintain.
View or download sample code (how to download)
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:
public interface IDateTime
{
DateTime Now { get; }
}
The following code implements the IDateTime
interface:
public class SystemDateTime : IDateTime
{
public DateTime Now
{
get { return DateTime.Now; }
}
}
Add the service to the service container:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.AddControllersWithViews();
}
For more information on AddSingleton, see DI service lifetimes.
The following code displays a greeting to the user based on the time of day:
public class HomeController : Controller
{
private readonly IDateTime _dateTime;
public HomeController(IDateTime dateTime)
{
_dateTime = dateTime;
}
public IActionResult Index()
{
var serverTime = _dateTime.Now;
if (serverTime.Hour < 12)
{
ViewData["Message"] = "It's morning here - Good Morning!";
}
else if (serverTime.Hour < 17)
{
ViewData["Message"] = "It's afternoon here - Good Afternoon!";
}
else
{
ViewData["Message"] = "It's evening here - Good Evening!";
}
return View();
}
Run the app and a message is displayed based on the time.
The FromServicesAttribute enables injecting a service directly into an action method without using constructor injection:
public IActionResult About([FromServices] IDateTime dateTime)
{
return Content( $"Current server time: {dateTime.Now}");
}
The following code shows how to access keyed services from the DI container by using the [FromKeyedServices]
attribute:
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
public interface ICache
{
object Get(string key);
}
public class BigCache : ICache
{
public object Get(string key) => $"Resolving {key} from big cache.";
}
public class SmallCache : ICache
{
public object Get(string key) => $"Resolving {key} from small cache.";
}
[ApiController]
[Route("/cache")]
public class CustomServicesApiController : Controller
{
[HttpGet("big")]
public ActionResult<object> GetBigCache([FromKeyedServices("big")] ICache cache)
{
return cache.Get("data-mvc");
}
[HttpGet("small")]
public ActionResult<object> GetSmallCache([FromKeyedServices("small")] ICache cache)
{
return cache.Get("data-mvc");
}
}
Accessing app or configuration settings from within a controller is a common pattern. The options pattern described in Options pattern in ASP.NET Core is the preferred approach to manage settings. Generally, don't directly inject IConfiguration into a controller.
Create a class that represents the options. For example:
public class SampleWebSettings
{
public string Title { get; set; }
public int Updates { get; set; }
}
Add the configuration class to the services collection:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.Configure<SampleWebSettings>(Configuration);
services.AddControllersWithViews();
}
Configure the app to read the settings from a JSON-formatted file:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("samplewebsettings.json",
optional: false,
reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
The following code requests the IOptions<SampleWebSettings>
settings from the service container and uses them in the Index
method:
public class SettingsController : Controller
{
private readonly SampleWebSettings _settings;
public SettingsController(IOptions<SampleWebSettings> settingsOptions)
{
_settings = settingsOptions.Value;
}
public IActionResult Index()
{
ViewData["Title"] = _settings.Title;
ViewData["Updates"] = _settings.Updates;
return View();
}
}
By Shadi Alnamrouti, Rick Anderson, and Steve Smith
ASP.NET Core MVC controllers request dependencies explicitly via constructors. ASP.NET Core has built-in support for dependency injection (DI). DI makes apps easier to test and maintain.
View or download sample code (how to download)
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:
public interface IDateTime
{
DateTime Now { get; }
}
The following code implements the IDateTime
interface:
public class SystemDateTime : IDateTime
{
public DateTime Now
{
get { return DateTime.Now; }
}
}
Add the service to the service container:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.AddControllersWithViews();
}
For more information on AddSingleton, see DI service lifetimes.
The following code displays a greeting to the user based on the time of day:
public class HomeController : Controller
{
private readonly IDateTime _dateTime;
public HomeController(IDateTime dateTime)
{
_dateTime = dateTime;
}
public IActionResult Index()
{
var serverTime = _dateTime.Now;
if (serverTime.Hour < 12)
{
ViewData["Message"] = "It's morning here - Good Morning!";
}
else if (serverTime.Hour < 17)
{
ViewData["Message"] = "It's afternoon here - Good Afternoon!";
}
else
{
ViewData["Message"] = "It's evening here - Good Evening!";
}
return View();
}
Run the app and a message is displayed based on the time.
The FromServicesAttribute enables injecting a service directly into an action method without using constructor injection:
public IActionResult About([FromServices] IDateTime dateTime)
{
return Content( $"Current server time: {dateTime.Now}");
}
Accessing app or configuration settings from within a controller is a common pattern. The options pattern described in Options pattern in ASP.NET Core is the preferred approach to manage settings. Generally, don't directly inject IConfiguration into a controller.
Create a class that represents the options. For example:
public class SampleWebSettings
{
public string Title { get; set; }
public int Updates { get; set; }
}
Add the configuration class to the services collection:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.Configure<SampleWebSettings>(Configuration);
services.AddControllersWithViews();
}
Configure the app to read the settings from a JSON-formatted file:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("samplewebsettings.json",
optional: false,
reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
The following code requests the IOptions<SampleWebSettings>
settings from the service container and uses them in the Index
method:
public class SettingsController : Controller
{
private readonly SampleWebSettings _settings;
public SettingsController(IOptions<SampleWebSettings> settingsOptions)
{
_settings = settingsOptions.Value;
}
public IActionResult Index()
{
ViewData["Title"] = _settings.Title;
ViewData["Updates"] = _settings.Updates;
return View();
}
}
See Test controller logic in ASP.NET Core to learn how to make code easier to test by explicitly requesting dependencies in controllers.
Replace the default dependency injection container with a third party implementation.
By Shadi Namrouti, Rick Anderson, and Steve Smith
ASP.NET Core MVC controllers request dependencies explicitly via constructors. ASP.NET Core has built-in support for dependency injection (DI). DI makes apps easier to test and maintain.
View or download sample code (how to download)
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:
public interface IDateTime
{
DateTime Now { get; }
}
The following code implements the IDateTime
interface:
public class SystemDateTime : IDateTime
{
public DateTime Now
{
get { return DateTime.Now; }
}
}
Add the service to the service container:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
For more information on AddSingleton, see DI service lifetimes.
The following code displays a greeting to the user based on the time of day:
public class HomeController : Controller
{
private readonly IDateTime _dateTime;
public HomeController(IDateTime dateTime)
{
_dateTime = dateTime;
}
public IActionResult Index()
{
var serverTime = _dateTime.Now;
if (serverTime.Hour < 12)
{
ViewData["Message"] = "It's morning here - Good Morning!";
}
else if (serverTime.Hour < 17)
{
ViewData["Message"] = "It's afternoon here - Good Afternoon!";
}
else
{
ViewData["Message"] = "It's evening here - Good Evening!";
}
return View();
}
Run the app and a message is displayed based on the time.
The FromServicesAttribute enables injecting a service directly into an action method without using constructor injection:
public IActionResult About([FromServices] IDateTime dateTime)
{
ViewData["Message"] = $"Current server time: {dateTime.Now}";
return View();
}
Accessing app or configuration settings from within a controller is a common pattern. The options pattern described in Options pattern in ASP.NET Core is the preferred approach to manage settings. Generally, don't directly inject IConfiguration into a controller.
Create a class that represents the options. For example:
public class SampleWebSettings
{
public string Title { get; set; }
public int Updates { get; set; }
}
Add the configuration class to the services collection:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDateTime, SystemDateTime>();
services.Configure<SampleWebSettings>(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Configure the app to read the settings from a JSON-formatted file:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("samplewebsettings.json",
optional: false, // File is not optional.
reloadOnChange: false);
})
.UseStartup<Startup>();
}
The following code requests the IOptions<SampleWebSettings>
settings from the service container and uses them in the Index
method:
public class SettingsController : Controller
{
private readonly SampleWebSettings _settings;
public SettingsController(IOptions<SampleWebSettings> settingsOptions)
{
_settings = settingsOptions.Value;
}
public IActionResult Index()
{
ViewData["Title"] = _settings.Title;
ViewData["Updates"] = _settings.Updates;
return View();
}
}
See Test controller logic in ASP.NET Core to learn how to make code easier to test by explicitly requesting dependencies in controllers.
Replace the default dependency injection container with a third party implementation.
ASP.NET Core feedback
ASP.NET Core is an open source project. Select a link to provide feedback:
Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreTraining
Module
Configure services with dependency injection in ASP.NET Core - Training
Understand and implement dependency injection in an ASP.NET Core app. Use ASP.NET Core's built-in service container to manage dependencies. Register services with the service container.