标签:imp 默认 项目文件 als unittest mock key connect value
示例:ASP.NET MVC
asp.net mvc已经内部实现了对配置appsettings.json文件的使用,builder默认支持热更新。
假设appsettings.json内容为:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
namespace webapp.Models
{
public class AppsettingsModel
{
public Logging Logging { get; set; }
public string AllowedHosts { get; set; }
}
public class Logging
{
public LogLevel LogLevel { get; set; }
}
public class LogLevel
{
public string Default { get; set; }
}
}
PS:
需要注意,用于IOptions或者IOptionsSnapshot中的模型的各个属性,其setter必须是公共的,不能是私有。
另外对于该模型,必须要有一个无参构造函数。
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// 依赖注入
services.Configure<AppsettingsModel>(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public class TestController : Controller
{
private readonly AppsettingsModel _appsettingsModel;
//若要使用热更新,则入参调整为 IOptionsSnapshot<T>
public TestController(IOptions<AppsettingsModel> appsettingsModel)
{
_appsettingsModel = appsettingsModel.Value;
}
public IActionResult Index()
{
return View("Index", _appsettingsModel.Logging.LogLevel.Default);
}
}
假设测试controller为
public class TestController : Controller
{
private readonly AppsettingsModel _appsettingsModel;
//使用的是:IOptionsSnapshot<T>
public TestController(IOptionsSnapshot<AppsettingsModel> appsettingsModel)
{
_appsettingsModel = appsettingsModel.Value;
}
public IActionResult Index()
{
return View("Index", _appsettingsModel.Logging.LogLevel.Default);
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) => //1.通过该方法来覆盖配置
{
//2.重新添加json配置文件
config.AddJsonFile("appsettings.json", false, false); //3.最后一个参数就是是否热更新的布尔值
})
.UseStartup<Startup>();
}
对于console项目,默认是没有这个dll的,需要自行从nuget安装
从nuget中安装:Microsoft.AspNetCore.All (注意,末尾不是dll,而是all)
在项目中引入:Microsoft.Extensions.Configuration; 并使用ConfigurationBuilder来构建配置。
在控制台项目属性中增加name和class参数:
使用:
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddCommandLine(args);
var configuration = builder.Build();
Console.WriteLine($"name:{configuration["name"]}"); //name:CLS
Console.WriteLine($"class:{configuration["class"]}"); //class:Class_A
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>
{
{"name","MC"},
{"class","CLASS_MC"}
};
var builder = new ConfigurationBuilder()
// .AddCommandLine(args)
.AddInMemoryCollection(dict);
var configuration = builder.Build();
Console.WriteLine($"name:{configuration["name"]}");//name:MC
Console.WriteLine($"class:{configuration["class"]}"); //class:CLASS_MC
Console.Read();
}
}
注意事项:
/*
假设 在项目属性中,定义的内容为:name=CLS,class=CLASS_CLS,grade="mygrade"
在代码中,dict的内容为:name=MC,class=CLASS_MC
*/
//对于代码:
var builder = new ConfigurationBuilder()
.AddCommandLine(args)
.AddInMemoryCollection(dict);
var configuration = builder.Build();
Console.WriteLine($"name:{configuration["name"]}");//name:MC
Console.WriteLine($"class:{configuration["class"]}"); //class:CLASS_MC
Console.WriteLine($"grade:{configuration["grade"]}"); //grade:mygrade
//对于代码:
var builder = new ConfigurationBuilder()
.AddInMemoryCollection(dict)
.AddCommandLine(args);
var configuration = builder.Build();
Console.WriteLine($"name:{configuration["name"]}");//name:CLS
Console.WriteLine($"class:{configuration["class"]}"); //class:CLASS_CLS
Console.WriteLine($"grade:{configuration["grade"]}"); //grade:mygrade
dotnet CommandLineSample.dll name=111 class=222 grade="my grade"
JSON文件内容:
{
"Class": "Class A",
"PersonInfo": {
"name": "my name",
"age": "12"
},
"Hobbies": [
{
"Type": "Family",
"HobbyName": "Piano"
},
{
"Type": "Personal",
"HobbyName": "Singing"
}
]
}
代码:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("jsconfig1.json");
var configuration = builder.Build();
Console.WriteLine($"name:{configuration["PersonInfo:name"]}");
Console.WriteLine($"class:{configuration["class"]}");
Console.WriteLine($"age:{configuration["PersonInfo:age"]}");
//注意下调用参数时的格式:"{参数Key}:{数组索引}:{子项参数Key}"
Console.WriteLine($"FamilyHobby:{configuration["Hobbies:0:HobbyName"]}");
Console.WriteLine($"PersonalHobby:{configuration["Hobbies:1:HobbyName"]}");
Console.Read();
}
引用上面的json:
{
"Class": "Class A",
"PersonInfo": {
"name": "my name",
"age": "12"
},
"Hobbies": [
{
"Type": "Family",
"HobbyName": "Piano"
},
{
"Type": "Personal",
"HobbyName": "Singing"
}
]
}
如何在注册的时候希望将PersonInfo这个section单独注入到 PersonInfo.cs类中?(以mvc为例)
public class PersonInfo
{
public string Name {get;set;}
public int Age{get;set;}
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// 依赖注入
services.Configure<PersonInfo>(Configuration.GetSection("PersonInfo"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public class TestController : Controller
{
private readonly PersonInfo _personInfo;
public TestController(IOptions<PersonInfo> personInfo)
{
_personInfo = _personInfo.Value;
}
public IActionResult Index()
{
return View("Index", _personInfo.Name);
}
}
//jwt
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
var jwtSettings = new JwtSettings();
Configuration.Bind("JwtSettings", jwtSettings);
services.AddSanbenTechJwtService(jwtSettings.Issuer, jwtSettings.Audience);
首先确保配置文件的属性:
nuget安装、引入必要的库:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json
在构造函数中使用配置文件:
public UnitTest1()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var settings = configuration.GetSection("RedisSettings").Get<RedisSettings>();
_mock.Setup(p => p.Value).Returns(settings);
}
https://docs.microsoft.com/zh-cn/aspnet/core/security/app-secrets?view=aspnetcore-2.2&tabs=windows
{
"Movies": {
"ServiceApiKey": "12345",
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=Movie-1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
配置模型:
public class MovieSettings
{
public string ConnectionString { get; set; }
public string ServiceApiKey { get; set; }
}
//使用
var moviesConfig = Configuration.GetSection("Movies").Get<MovieSettings>();
_moviesApiKey = moviesConfig.ServiceApiKey;
在.NET CORE中使用配置文件:对 ConfigurationBuilder 的使用说明
标签:imp 默认 项目文件 als unittest mock key connect value
原文地址:https://www.cnblogs.com/deepthought/p/11297849.html