本文介绍了将加载配置添加到asp.net Core中的注入依赖项中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.Net Core API中,我使用Startup.cs中的services.AddTransient方法注入了一些存储库类

In my Asp.Net Core API, I have some repository classes I'm injecting by using the services.AddTransient method in my Startup.cs

services.AddTransient<IRepository, Repository>();

我还将appsettings.json的一部分加载到Startup.cs中的自定义对象中

I'm also loading a section of my appsettings.json into a custom object in the Startup.cs

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

我的存储库类需要从appsettings.json加载数据库连接字符串.有没有办法将这些设置直接注入到存储库类中?还是由控制器的构造函数将连接字符串传递到存储库类?

My repository class needs to load the db connection string from the 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;
    }

其中MyConfig是您配置的POCO对象,并在启动时被添加/注册:

where MyConfig is a POCO object of your configuration and is getting added/registered in startup:

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

MyConfig看起来可能像这样:

The MyConfig can look something like this:

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

和appsettings.json一样:

And the appsettings.json like this:

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

这篇关于将加载配置添加到asp.net Core中的注入依赖项中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:31