首页 > 其他 > 详细

依赖注入之IConfiguration

时间:2019-07-26 11:52:20      阅读:346      评论:0      收藏:0      [点我收藏+]
  public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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)
        {
            services.AddMvc();
//下面这行就是注入 services.Configure
<AppSettings>(Configuration.GetSection("AppSettings"));//这里是添加的,其余的都是新建项目带的
//AppSettings这个类是新增的,里面的字段,对应appsettings.json中的字段

//链接字符串的
var conn = Configuration.GetSection("ConnectionStrings");
          string efconn = conn["acc_miniehub"];
//映射的实体类的ConnectionString 属性
 OMSECData.Acc_OmsContext.ConnectionString = efconn;
            services.AddDbContext<OMSECData.Acc_OmsContext>
            (
                options => options.UseSqlServer(efconn)
            );


}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } }

技术分享图片

应用:这样就ok了。appsetting.json就是配置文件,把什么链接字符串了什么都是放在这里的。

技术分享图片

 

 链接数据库:

技术分享图片

 

用法和前面的一样,先声明再注入

 

IConfiguration 是用来加载配置值的,可以加载内存键值对、JSON或XML配置文件,我们通常用来加载缺省的appsettings.json 

1. 注入IConfiguration

执行到Startup的时候,IConfiguration已经被注入到services了,不需要我们额外添加注入的代码,缺省就是读取appsettings.json文件,你可以理解在Startup.cs里有隐藏的注入代码类似如下:

var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
Configuration = builder.Build();
services.AddSingleton<IConfiguration>(Configuration);

 

依赖注入之IConfiguration

原文:https://www.cnblogs.com/ZkbFighting/p/11248798.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!