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
执行到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);
原文:https://www.cnblogs.com/ZkbFighting/p/11248798.html