简体   繁体   English

在asp.net核心中将加载配置添加到注入依赖项中

[英]Adding loading configuration into inject dependencies in asp.net core

In my Asp.Net Core API, I have some repository classes I'm injecting by using the services.AddTransient method in my Startup.cs 在我的Asp.Net Core API中,我有一些我正在使用我的Startup.cs中的services.AddTransient方法注入的存储库类。

services.AddTransient<IRepository, Repository>();

I'm also loading a section of my appsettings.json into a custom object in the Startup.cs 我还将我的appsettings.json的一部分加载到Startup.cs中的自定义对象中

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

My repository class needs to load the db connection string from the appsettings.json. 我的存储库类需要从appsettings.json加载数据库连接字符串。 Is there a way to inject these settings straight to the repository class? 有没有办法将这些设置直接注入存储库类? Or is it up to the constructor of the controller to pass the connection string to the repository class? 或者是由控制器的构造函数将连接字符串传递给存储库类?

Yes, you can inject this directly to your repository. 是的,您可以将其直接注入您的存储库。

    public MyRepository(IOptions<MyConfig> config)
    {
        var connString = config.Value.DbConnString;
    }

where MyConfig is a POCO object of your configuration and is getting added/registered in startup: 其中MyConfig是您的配置的POCO对象,并在启动时添加/注册:

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

The MyConfig can look something like this: MyConfig看起来像这样:

    public class MyConfig
    {
        public string DbConnString { get; set; }
    }

And the appsettings.json like this: 和appsettings.json这样:

{
  "ApplicationName": "MyApp",
  "Version": "1.0.0",
  "DbConnString ": "my-conn-string"
}

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

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