简体   繁体   English

ASP.NET Core-DI-使用操作 <T> 或IOption <T>

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

I'm trying to understand the different between using IOptions<T> and Action<T> and when to use what. 我试图了解使用IOptions<T>Action<T>以及何时使用什么之间的区别。

I have a library that is using an extension method for IServiceCollection where I need to configure my service as well as configure a EF DbContext . 我有一个库,该库使用IServiceCollection的扩展方法,需要在其中配置我的服务以及EF DbContext

Example: 例:

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

How do I get the ConnectionString property value from the SomeOptionsClass ? 如何从SomeOptionsClass获取ConnectionString属性值?

Not sure why the need for IOptions<T> here. 不知道为什么在这里需要IOptions<T>

Should be able to get the connection string from Configuration ( appsetting ) during startup. 启动期间应该能够从Configuration( appsetting )获取连接字符串。 IOptions<T> is usually used for injecting setting into classes IOptions<T>通常用于将设置注入类

I suggest simplifying the API to expect the connection string 我建议简化API以期望连接字符串

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

This would allow users more flexibility when configuring the module. 这将使用户在配置模块时具有更大的灵活性。

For example in the configure services in composition root you can access configuration and extract the connection string to be used as needed 例如,在组合根目录中的configure services中,您可以访问配置并提取连接字符串以根据需要使用

//...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM