[英]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>
。
启动期间应该能够从Configuration( appsetting )获取连接字符串。 IOptions<T>
通常用于将设置注入类
我建议简化API以期望连接字符串
namespace Microsoft.Extensions.DependencyInjection {
public static void AddModule(this IServiceCollection services, string connectionString) {
services.AddDbContext<MyContext>(contextOptions => contextOptions.UseSqlServer(connectionString));
}
}
这将使用户在配置模块时具有更大的灵活性。
例如,在组合根目录中的configure services中,您可以访问配置并提取连接字符串以根据需要使用
//...
services.AddModule(Configuration["Appsettings Key Here"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.