ASP.NET 核心 - DI - 使用 Action<T> 或 IOption<T>

ASP.NET Core - DI - Using Action<T> or IOption<T>

我正在尝试了解使用 IOptions<T>Action<T> 之间的区别以及何时使用什么。

我有一个库正在使用 IServiceCollection 的扩展方法,我需要在其中配置我的服务以及配置 EF DbContext.

示例:

namespace Microsoft.Extensions.DependencyInjection 
{
    public static void AddModule(this IServiceCollection services, IOptions<SomeOptionsClass> options) {
        services.AddDbContext<MyContext>(contextOptions => contextOptions.UseSqlServer(SomeOptionsClass.ConnectionString));
    }
}

如何从 SomeOptionsClass 中获取 ConnectionString 属性 值?

不知道为什么这里需要 IOptions<T>

应该能够在启动期间从配置 (appsetting) 获取连接字符串。 IOptions<T> 通常用于将设置注入 类

我建议简化 API 以期待连接字符串

namespace Microsoft.Extensions.DependencyInjection  {
    public static void AddModule(this IServiceCollection services, string connectionString) {
        services.AddDbContext<MyContext>(contextOptions => contextOptions.UseSqlServer(connectionString));
    }
}

这将使用户在配置模块时更加灵活。

例如,在 composition root 中的配置服务中,您可以访问配置并提取连接字符串以根据需要使用

//...

services.AddModule(Configuration["Appsettings Key Here"]);