【问题标题】:Initialize Class with IOptions Injection Issue使用 IOptions 注入问题初始化类
【发布时间】:2019-01-29 17:39:54
【问题描述】:

我刚开始用 net core 2.1 构建一个 API。

我在 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"
  }

首先我在 startup.cs 中添加了配置管理器,以便可以注入其他类

startup.cs

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

我有一个初始化 SQLConnection 的类,但我需要注入 appsettings 以便读取连接字符串。

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

      }

但是我想从另一个班级打电话。

CustomSqlConnection connection = new CustomSqlConnection()

但是,IOptions&lt;MyConfig&gt; _Config 显示为空。

初始化注入 IOptions 或任何其他接口的类的最佳做法是什么。

【问题讨论】:

  • 也许Configuration.GetSection("MySettings")
  • 只是需要澄清一下。您的MyConfig 类与`appsettings.json 相同,对吧?
  • 是的,它是一样的。顺便说一句,找不到 Configuration.GetSection。

标签: c# asp.net-core dependency-injection .net-core


【解决方案1】:

Configuration.GetSection("MySettings") 将尝试在 appsettings.json 文件中查找“MySettings”部分。

MySettings 类应如下所示

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

然后在启动中您将能够配置MySettings 的选项

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

以及设置的使用

public class SomeClass
{
    private readonly MySettings _settings;

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

【讨论】:

  • 但是如何初始化 SomeClass?喜欢新的 SomeClass()?
  • @MissakBoyajian,依赖注入的想法,你不知道。您需要注册类并作为将使用它的类的构造函数参数引入。
【解决方案2】:

也许先从 json 中获取设置,这样您就可以查看它是否正常工作,然后进行配置。

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

那么,如果正确的话:

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

另外,请确保您已安装以下 NuGet 包:

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

【讨论】:

  • configuration.GetSection 不起作用,我注入了所有这些包。也许我只是注意到 cz 它是 2.1 ?
  • 检查 appsettings.json 的属性。也许它没有被复制到构建目录。
【解决方案3】:

你可以在你正在初始化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
    }
}

更新:

您只需要在其他类中使用其接口IYourNewClass 注入该类。

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

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

在你的 startup.cs 中,在 mvc 之前配置你的 appsettings。

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

【讨论】:

  • 问题是,如果我必须初始化YourNewClass,我必须再次经历同样的过程。
  • 在编辑后的答案中,您可以看到如何使用YourNewClass@MissakBoyajian
猜你喜欢
  • 2020-10-17
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多