简体   繁体   English

使用IOptions注入问题初始化类

[英]Initialize Class with IOptions Injection Issue

I just started to build an API with net core 2.1. 我刚刚开始使用Net Core 2.1构建API。

I added my connection string in appsettings.json and I want to access it. 我在appsettings.json中添加了连接字符串,我想访问它。

appsettings.json 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中添加了配置管理器,以便可以注入其他类

startup.cs 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. 我有一个用于初始化SQLConnection的类,但我需要注入appsettings以便读取连接字符串。

ConnectionManager.cs 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. 但是, IOptions<MyConfig> _Config向我显示了null。

What is the best practice to initialize a class that injects IOptions or any other interface. 初始化注入IOptions或任何其他接口的类的最佳实践是什么。

Configuration.GetSection("MySettings") will try to find a "MySettings" section inside of appsettings.json file. Configuration.GetSection("MySettings")将尝试在appsettings.json文件内找到“ MySettings”部分。

MySettings class should look like below MySettings类应如下所示

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 然后,在启动中,您将能够配置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. 也许首先从json获取设置,以便您可以查看它是否正常运行,然后进行配置。

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: 此外,请确保已安装以下NuGet软件包:

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

You can use dependency injection in the class you are initializing CustomSqlConnection object. 您可以在初始化CustomSqlConnection对象的类中使用依赖项注入。

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. 您只需要在其他类中使用其接口IYourNewClass注入该类。

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. 并在您的startup.cs中确实在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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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