ASP.NET Core 中文文档 第四章 MVC(4.4)依赖注入和控制器
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:50
ASP.NET Core MVC 控制器应通过它们的构造器明确的请求它们的依赖关系。在某些情况下,单个控制器的操作可能需要一个服务,在控制器级别上的请求可能没有意义。在这种情况下,你也可以选择将服务作为 action 方法的参数。
章节:
依赖注入依赖注入(Dependency injection,DI)是一种如 Dependency Inversion Principle 所示的技术,允许应用程序由松散耦合的模块组成。ASP.NET Core 内置了 dependency injection,这使得应用程序更容易测试和维护。
构造器注入ASP.NET Core 内置的基于构造器的依赖注入支持扩展到 MVC 控制器。通过只添加一个服务类型作为构造器参数到你的控制器中,ASP.NET Core 将会尝试使用内置的服务容器解析这个类型。服务通常是,但不总是使用接口来定义。例如,如果你的应用程序存在取决于当前时间的业务逻辑,你可以注入一个检索时间的服务(而不是对它硬编码),这将允许你的测试通过一个使用设置时间的实现。
using System;
namespace ControllerDI.Interfaces
{
public interface IDateTime
{
DateTime Now { get; }
}
}
实现这样一个接口,它在运行时使用的系统时钟是微不足道的:
using System;
using ControllerDI.Interfaces;
namespace ControllerDI.Services
{
public class SystemDateTime : IDateTime
{
public DateTime Now
{
get { return DateTime.Now; }
}
}
}
HomeControllerIndex
using ControllerDI.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace ControllerDI.Controllers
{
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(); //手动高亮
}
}
}
如果我们现在运行应用程序,我们将可能遇到一个异常:
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'ControllerDI.Interfaces.IDateTime' while attempting to activate 'ControllerDI.Controllers.HomeController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
StartupConfigureServicesIDateTimeSystemDateTimeConfigureServices
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddTransient<IDateTime, SystemDateTime>(); //手动高亮
}
TransientScopedSingleton
一旦服务被配置,运行应用程序并且导航到首页应该显示预期的基于时间的消息:

ASP.NET Core 内置的依赖注入支持用于请求服务的类型只有一个构造器。如果你有多于一个构造器,你可能会得到一个异常描述:
An unhandled exception occurred while processing the request.
InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'ControllerDI.Controllers.HomeController'. There should only be one applicable constructor.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, ConstructorInfo& matchingConstructor, Nullable`1[]& parameterMap)
作为错误消息状态,你可以纠正只有一个构造器的问题。你也可以参考 replace the default dependency injection support with a third party implementation 支持多个构造器。
Action 注入和 FromServices[FromServices]
public IActionResult About([FromServices] IDateTime dateTime) //手动高亮
{
ViewData["Message"] = "Currently on the server the time is " + dateTime.Now;
return View();
}
从控制器访问设置
IOptionsT
要使用选项模式,你需要创建一个表示选项的类型,如:
namespace ControllerDI.Model
{
public class SampleWebSettings
{
public string Title { get; set; }
public int Updates { get; set; }
}
}
ConfigureServices
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder() //手动高亮
.SetBasePath(env.ContentRootPath) //手动高亮
.AddJsonFile("samplewebsettings.json"); //手动高亮
Configuration = builder.Build(); //手动高亮
}
public IConfigurationRoot Configuration { get; set; } //手动高亮
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// Required to use the Options<T> pattern
services.AddOptions(); //手动高亮
// Add settings from configuration
services.Configure<SampleWebSettings>(Configuration); //手动高亮
// Uncomment to add settings from code
//services.Configure<SampleWebSettings>(settings =>
//{
// settings.Updates = 17;
//});
services.AddMvc();
// Add application services.
services.AddTransient<IDateTime, SystemDateTime>();
}
注意
在上面的清单中,我们配置应用程序程序从一个 JSON 格式的文件中读取设置。你也可以完全在代码中配置设置,像上面的代码中所显示的。参考 configuration 更多的配置选项。
SampleWebSettingsIOptionsIOptions
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();
}
}
遵循选项模式允许设置和配置互相分离,确保控制器遵循 separation of concerns ,因为它不需要知道如何或者在哪里找到设置信息。由于没有 static cling 或在控制器中直接实例化设置类,这也使得控制器更容易单元测试 。
相关文章
-
ASP.Net Core2.1中的HttpClientFactory系列二:集成Polly处理瞬态故障
ASP.Net Core2.1中的HttpClientFactory系列二:集成Polly处理瞬态故障
- 互联网
- 2026年04月04日
-
ASP.NET Core应用的错误处理[3]:ExceptionHandlerMiddleware中间件如何呈现“定制化错误页面”
ASP.NET Core应用的错误处理[3]:ExceptionHandlerMiddleware中间件如何呈现“定制化错误页面”
- 互联网
- 2026年04月04日
-
ASP.NET Core中如影随形的”依赖注入”[上]: 从两个不同的ServiceProvider说起
ASP.NET Core中如影随形的”依赖注入”[上]: 从两个不同的ServiceProvider说起
- 互联网
- 2026年04月04日
-
ASP.NET Core 中文文档 第四章 MVC(4.3)过滤器
ASP.NET Core 中文文档 第四章 MVC(4.3)过滤器
- 互联网
- 2026年04月04日
-
ASP.NET Core 中文文档 第四章 MVC(3.9)视图组件
ASP.NET Core 中文文档 第四章 MVC(3.9)视图组件
- 互联网
- 2026年04月04日
-
ASP.NET Core 中文文档 第四章 MVC(01)ASP.NET Core MVC 概览
ASP.NET Core 中文文档 第四章 MVC(01)ASP.NET Core MVC 概览
- 互联网
- 2026年04月04日








