C# asp.net core-使用IServiceCollection扩展中的选项添加服务
我正在尝试在C# asp.net core-使用IServiceCollection扩展中的选项添加服务,c#,asp.net-core,C#,Asp.net Core,我正在尝试在Startup.cs中注册我的自定义服务。此服务的配置选项之一是ConnectionString。我想使用这个连接字符串在扩展内注册专用的DbContext,但不知道如何访问选项(连接字符串)。在这个层次上是可能的还是我应该使用不同的方法 这是我的分机: public static IServiceCollection AddUniLocalizer( this IServiceCollection services, Action<ServiceOptions
Startup.cs
中注册我的自定义服务。此服务的配置选项之一是ConnectionString。我想使用这个连接字符串在扩展内注册专用的DbContext,但不知道如何访问选项(连接字符串)。在这个层次上是可能的还是我应该使用不同的方法
这是我的分机:
public static IServiceCollection AddUniLocalizer(
this IServiceCollection services,
Action<ServiceOptions> setupAction)
{
services.Add(new ServiceDescriptor(typeof(IStringLocalizerFactory),
typeof(UniLocalizerFactory), ServiceLifetime.Singleton));
services.Add(new ServiceDescriptor(typeof(IStringLocalizer),
typeof(UniLocalizer), ServiceLifetime.Singleton));
var connectionString = null; // ????????? How to connection string it from ServiceOptions instance?
services.AddDbContext<LocalizerDbContext>(
item => item.UseSqlServer(connectionString));
return services;
}
使用操作时,这是不可能的,因为: Action也是在系统命名空间中定义的委托类型。一 动作类型委托与Func委托相同,只是 动作委托不返回值。换言之,是一种行动 委托可与具有void返回类型的方法一起使用 因此,要么使用Func,要么使用普通对象 我建议用最后一个 再想一想,为什么不提供配置,因为您可能希望在appSettings中使用connectionString:
public static IServiceCollection AddSecurity(this IServiceCollection services, IConfiguration configuration)
{
var appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
// configure jwt authentication
var secret = Encoding.ASCII.GetBytes(appSettings.Secret);
}
配置它本身可以在启动时注入您能提供一个使用
普通对象
的示例吗?您确定我可以在这里使用普通对象吗?动作模式似乎是服务生命周期更广泛概念的一部分。据我所知,可在实际服务注册之后对选项进行评估。或。。也许你的意思是向扩展添加另一个参数(除了setupAction)?是的,添加了另一个参数。我添加了另一个参数,它似乎工作正常。直接从appsettings读取配置的想法也很好。谢谢你的帮助!
public static IServiceCollection AddSecurity(this IServiceCollection services, IConfiguration configuration)
{
var appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
// configure jwt authentication
var secret = Encoding.ASCII.GetBytes(appSettings.Secret);
}
services.AddSecurity(Configuration)