简体   繁体   中英

Initialize Class with IOptions Injection Issue

I just started to build an API with net core 2.1.

I added my connection string in appsettings.json and I want to access it.

appsettings.json

  "MySettings": {
    "connectionString": "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Subscription;Data Source=Test-Pc",
    "Email": "abc@domain.com",
    "SMTPPort": "5605"
  }

First I added the configuration manager in startup.cs so that I can inject in other classes

startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure<MyConfig>(Configuration.GetSection("appsettings"));
        }

I have a class in which I initialize my SQLConnection, but I need to inject the appsettings so that I read the connection string.

ConnectionManager.cs

    public class CustomSqlConnection : IDisposable
    {
        private SqlConnection sqlConn;
        private readonly IOptions<MyConfig> _myConfig;

        public CustomSqlConnection(IOptions<MyConfig> _Config = null)
        {
            _myConfig = _Config;

            string connectionString = _myConfig.Value.connectionString;

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception(string.Format("Connection string was not found in config file"));
            }

            this.sqlConn = new SqlConnection(connectionString);
        }

      }

However I want to call from another class.

CustomSqlConnection connection = new CustomSqlConnection()

However, IOptions<MyConfig> _Config is showing me null.

What is the best practice to initialize a class that injects IOptions or any other interface.

Configuration.GetSection("MySettings") will try to find a "MySettings" section inside of appsettings.json file.

MySettings class should look like below

public class MySettings
{
    public string connectionString { get; set; }
    public string Email { get; set; }
    public string SMTPPort { get; set; }
}

Then in Startup you will be able to configure the options for MySettings

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.Configure<MyConfig>(Configuration.GetSection("MySettings"));
}

And usage of settings

public class SomeClass
{
    private readonly MySettings _settings;

    public SomeClass(IOptions<MySettings> setitngs)
    {
        _settings = setitngs.Value // notice of using a .Value property
    }
}

Maybe get the settings from json first so you can see if that is working correctly and then configure.

var config = configuration.GetSection("MySettings").Get<MyConfig>();

Then, if that works correctly:

services.Configure<MyConfig>(opts => 
{
    // map the properties here
    // opts.Property1 = config.Property1;
}

Also, ensure that you have the following NuGet packages installed:

Microsoft.Extensions.Configuration.Binder, Microsoft.Extensions.Configuration.Json, Microsoft.Extensions.DependencyInjection

You can use dependency injection in the class you are initializing CustomSqlConnection object.

public class YourNewClass : IYourNewClass
{    
    private CustomSqlConnection _connection { get; set; }
    //inject IOption here
    public YourNewClass(IOptions<MyConfig> _config)
    {
       _connection = new CustomSqlConnection(_config); //use this instance for all the repository methods
    }
}

UPDATE:

You only need to inject the class using its interface IYourNewClass in other classes.

public class SomeRandomClass
{    
    private IYourNewClass _newClass { get; set; }

    public SomeRandomClass(IYourNewClass newClass)
    {
       _newClass = newClass;
    }
}

And in your startup.cs do configure your appsettings before mvc.

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.Development.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //do all needed service registrations
        services.Configure<SpotMyCourtConfiguration>(Configuration);           
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //do all needed functionalities
        app.UseMvc();
    }
}

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