配置
- Key-Value 键值对
- 内存,JSON,XML,INI,环境变量,启动参数
- 从配置系统解耦
- 为依赖注入优化
查看 Program 类 CreateDefaultBuilder 的源码:
- AddJsonFile 依次加载了默认的配置文件和基于环境变量名的配置文件
- 如果两个配置文件中有重复的键值对,取下面一个的为准
- AddEnvironmentVaiables 从环境变量加载配置
IConfiguration
通过在 Startup 里面依赖注入 IConfiguration,可以将 json 配置文件的属性和实体类的属性相绑定。
JSON:
"ConnectionStrings": {
"DefaultConnection": "Database=InMemory;"
}
class:
namespace CoreDemo.Settings
{
public class ConnectionOptions
{
public string DefaultConnection { get; set; }
}
}
Startup:
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
...
// 和实体类的属性相绑定
services.Configure<ConnectionOptions>(_configuration.GetSection("ConnectionStrings"));
}
...
}
具体使用
注入到 Controller 中使用:
public class HomeController : Controller
{
private readonly ICinemaService _cinemaService;
private readonly IOptions<ConnectionOptions> _options;
public HomeController(ICinemaService cinemaService,IOptions<ConnectionOptions> options)
{
_cinemaService = cinemaService;
_options = options;
}
...
}
在视图中注入使用:
@inject IOptions<ConnectionOptions> options
<span>@options.Value.DefaultConnection</span>
自定义配置
View Component
以前有 Partial View,但是无法包含业务逻辑,Controller 里的逻辑也无法复用。
View Component 的优势:
- 前端项目中创建 ViewComponents 文件夹
- 创建以 ViewComponent 结尾的类
- 在 Views\Shared\Components\MovieCount 下创建默认视图文件 Default.cshtml
MovieCountViewComponent:
using System.Linq;
using System.Threading.Tasks;
using CoreDemo.Services;
using Microsoft.AspNetCore.Mvc;
namespace CoreDemo.ViewComponents
{
public class MovieCountViewComponent : ViewComponent
{
private readonly IMovieService _movieService;
public MovieCountViewComponent(IMovieService movieService)
{
_movieService = movieService;
}
// IViewComponentResult 类似于 Controller 里面的 IActionResult
public async Task<IViewComponentResult> InvokeAsync(int cinemaId)
{
var movies = await _movieService.GetByCinemaAsync(cinemaId);
var count = movies.Count();
return View(count);
}
}
}
Default.cshtml:
@model int
<h2>Movie Count:</h2>
<h2>@Model</h2>
使用
通过 :
@await Component.InvokeAsync("MovieCount", new { cinemaId = ViewBag.CinemaId })
类似于 HTML 标签的用法:
<vc:movie-count cinema-id="@ViewBag.CinemaId"></vc:movie-count>
注:第二种用法需先在 _ViewImports 里面引入当前项目:
@addTagHelper "*, CoreDemo"