温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET中怎么注入 Configuration

发布时间:2021-07-24 13:41:52 来源:亿速云 阅读:184 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关ASP.NET中怎么注入 Configuration,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

 

咨询区

LP13

我已经通读了 MSDN 上关于 Configuration 的相关内容,文档说可实现在 application 的任意位置访问 Configuration .

下面是 Startup.cs 的模板代码。


public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsEnvironment("Development"))
        {
            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(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, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseMvc();
    }
}

 

我知道可以通过 DI 的方式将 Configuration 注入到 Controller,Service,Repository 等地方,但在真实项目中,会有很多类是在这三块之外的。

请问我如何在这三大块之外实现 Configuration 的注入呢?换句话说:可以在任意类中实现 Configuration 的注入... ????

 

回答区

Mayer Spitzer

在 .NET Core 中你可以将 IConfiguration 作为参数直接注入到 Class 的构造函数中,这本身就是可以的,如下代码所示:


public class MyClass 
{
    private IConfiguration configuration;
    public MyClass(IConfiguration configuration)
    {
        ConnectionString = new configuration.GetValue<string>("ConnectionString");
    }
}

 

接下来要做的就是 new MyClass(),很显然这样做是不行的,因为你的构造函数还需要一个 IConfiguration 类型的参数,所以你需要将 new MyClass() 塞入到 Asp.NET Core 的 DI 链中。

思路也很简单。

  • 将 MyClass 注入到 ServiceCollection 容器中

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<MyClass>();
            services.AddControllers();
        }

 
  • 生成 MyClass 实例

在 MyClass 的调用方处通过 DI 生成实例,这里以 Controller 处为例,如下代码所示:


public class MyController : ControllerBase
{
    private MyClass _myClass;

    public MyController(MyClass myClass)
    {
        _myClass = myClass;
    }
}

 

这样是不是就完美的实现了在 MyClass 中使用 Configuration 了?

还有一种更简单粗暴的做法,无需注入, 只需定义一个静态的类,在 Startup 中将 IConfiguration 赋值给该静态类保存即可,参考代码如下:


public static class MyAppData
{
    public static IConfiguration Configuration;
}


public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    MyAppData.Configuration = configuration;
}

 

然后就可以在项目的各处访问 MyAppData.Configuration 啦。

 

点评区

在 Asp.Net 时代,读取配置文件真的是一点都不需要操心,一个 ConfigurationManager 走天下????????????,比如下面的代码:

    private static string AppKey = ConfigurationManager.AppSettings["AppKey"];

关于ASP.NET中怎么注入 Configuration就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI