最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ASP.NET Core中的键控依赖注入

网站源码admin6浏览0评论

ASP.NET Core中的键控依赖注入

大家好,我是深山踏红叶,今天我们来聊一聊 ASP.NET Core中的 FromKeyedServices,它是在 .Net 8 中引入的。这一特性允许通过键(如字符串或枚举)来注册和检索依赖注入(DI)服务,从而支持一对多的依赖注入模式,个人感觉最主要的还是不用写 构造函数注入了 。下面我们来看一下键控依赖注入的使用。

普通构造函数注入

构造函数注入是 ASP.NET Core 中最常用的依赖项注入方式。服务通过构造函数参数添加,并在运行时从服务容器中解析。

获取当前时间

1. 定义服务接口

代码语言:javascript代码运行次数:0运行复制
public interface IDateTime
{
    DateTime Now { get; }
}

2. 实现服务接口

代码语言:javascript代码运行次数:0运行复制
public class SystemDateTime : IDateTime
{
    public DateTime Now => DateTime.Now;
}

3. 注册服务到服务容器

代码语言:javascript代码运行次数:0运行复制
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();
    services.AddControllersWithViews();
}

4. 在控制器中使用

代码语言:javascript代码运行次数:0运行复制
public classHomeController : Controller
{
    privatereadonly IDateTime _dateTime;

    public HomeController(IDateTime dateTime)
    {
        _dateTime = dateTime;
    }

    public IActionResult Index()
    {
        var serverTime = _dateTime.Now;
        if (serverTime.Hour < )
        {
            ViewData["Message"] = "It's morning here - Good Morning!";
        }
        elseif (serverTime.Hour < )
        {
            ViewData["Message"] = "It's afternoon here - Good Afternoon!";
        }
        else
        {
            ViewData["Message"] = "It's evening here - Good Evening!";
        }
        return View();
    }
}

使用 FromServices 的操作注入

FromServices 属性允许直接将服务注入到操作方法中,而无需通过构造函数注入。

代码语言:javascript代码运行次数:0运行复制
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
     
    [HttpGet(Name = "GetWeatherForecast")]
    public IActionResult About([FromServices] IDateTime dateTime)
    {
        return Content($"Current server time: {dateTime.Now}");
    }
}

使用 FromKeyedServices 的操作注入

FromKeyedServices 属性允许从 DI 容器中访问键控服务。

代码语言:javascript代码运行次数:0运行复制
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();

publicinterfaceICache
{
    object Get(string key);
}

publicclassBigCache : ICache
{
    public object Get(string key) => $"Resolving {key} from big cache.";
}

publicclassSmallCache : ICache
{
    public object Get(string key) => $"Resolving {key} from small cache.";
}

[ApiController]
[Route("/cache")]
publicclassCustomServicesApiController : 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");
    }
}

从控制器访问设置

从控制器访问应用或配置设置是一种常见模式。推荐使用选项模式(Options Pattern)来管理设置。

1. 定义配置类

代码语言:javascript代码运行次数:0运行复制
public class SampleWebSettings
{
    public string Title { get; set; }
    public int Updates { get; set; }
}

2. 注册配置类到服务容器

代码语言:javascript代码运行次数:0运行复制
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();
    services.Configure<SampleWebSettings>(Configuration);
    services.AddControllersWithViews();
}

3. 从 JSON 文件加载配置

代码语言:javascript代码运行次数:0运行复制
public classProgram
{
    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>();
            });
}

4. 在控制器中使用配置

代码语言:javascript代码运行次数:0运行复制
public classSettingsController : Controller
{
    privatereadonly SampleWebSettings _settings;

    public SettingsController(IOptions<SampleWebSettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _settings.Title;
        ViewData["Updates"] = _settings.Updates;
        return View();
    }
}

参考:在 ASP.NET Core 中将依赖项注入到控制器

总结

键控依赖注入是 ASP.NET Core 中一个强大的功能,尤其适用于需要灵活切换实现的场景。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2025-04-17,如有侵权请联系 cloudcommunity@tencent 删除依赖注入aspcore服务配置

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论