asp.net核心-使用iSide IServiceCollection扩展选项的AddService

时间:2019-11-29 09:28:09

标签: c# asp.net-core

我正在尝试在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;
}

和用法(Startup.cs):

AddUniLocalizer(opt => { opt.conncetionString = "my connection string"; });

1 个答案:

答案 0 :(得分:1)

使用“操作”无法实现以下操作:

  

Action也是在System名称空间中定义的委托类型。一个   动作类型委托与Func委托相同,除了   动作委托不返回值。换句话说,一个动作   委托可以与具有无效返回类型的方法一起使用。

所以您必须使用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);
    }

当然,您使用的是您自己的实现。

在启动时拨打此电话:

services.AddSecurity(Configuration)

可以将其自身配置注入启动中