简体   繁体   中英

asp.net core - AddService using options iniside IServiceCollection extension

I'm trying to register my custom service in Startup.cs . One of configuration options of this service is ConnectionString. I would like to use this connection string to register dedicated DbContext inside extension, but don't know how to access options (connection string). Is it possible at this level or should I use different approach?

Here's my extension:

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;
}

And usage (Startup.cs):

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

With using a Action this is not possible as:

Action is also a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type.

So either you have to use Func or a plain object.

I Suggest to use the last one.

A second thought, why not providing the configuration as you probably want to have the connectionString in your 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);
    }

Of course you're are using you're own implementation.

Call to this from the startup:

services.AddSecurity(Configuration)

Configuration it self could be injected int the startup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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