How can I pass a runtime parameter as part of the dependency resolution?

前端 未结 5 1871
不知归路
不知归路 2021-01-30 10:28

I need to be able to pass a connection string into some of my service implementations. I am doing this in the constructor. The connection string is configurable by user will be

5条回答
  •  时光取名叫无心
    2021-01-30 11:04

    Simple configuration

    public void ConfigureServices(IServiceCollection services)
    {
        // Choose Scope, Singleton or Transient method
        services.AddSingleton();
        services.AddSingleton(serviceProvider=>
        {
             return new NestedService("someConnectionString");
        });
    }
    

    With appSettings.json

    If you decide to hide your connection string inside appSettings.json, e.g:

    "Data": {
      "ConnectionString": "someConnectionString"
    }
    

    Then provided that you've loaded your appSettings.json in the ConfigurationBuilder (usually located in the constructor of the Startup class), then your ConfigureServices would look like this:

    public void ConfigureServices(IServiceCollection services)
    {
        // Choose Scope, Singleton or Transient method
        services.AddSingleton();
        services.AddSingleton(serviceProvider=>
        {
             var connectionString = Configuration["Data:ConnectionString"];
             return new NestedService(connectionString);
        });
    }
    

    With extension methods

    namespace Microsoft.Extensions.DependencyInjection
    {
        public static class RootServiceExtensions //you can pick a better name
        {
            //again pick a better name
            public static IServiceCollection AddRootServices(this IServiceCollection services, string connectionString) 
            {
                // Choose Scope, Singleton or Transient method
                services.AddSingleton();
                services.AddSingleton(_ => 
                  new NestedService(connectionString));
            }
        }
    }
    

    Then your ConfigureServices method would look like this

    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration["Data:ConnectionString"];
        services.AddRootServices(connectionString);
    }
    

    With options builder

    Should you need more parameters, you can go a step further and create an options class which you pass to RootService's constructor. If it becomes complex, you can use the Builder pattern.

提交回复
热议问题