我在vnext项目中实现了一个Custom ViewLocationExpander。我想从ViewLocationExpander中的appsettings.json文件中读取应用程序设置值,因此IOptions<>已经注入到自定义ViewLocationExpander的构造函数中。但是,在将自定义ViewLocationExpander添加到RazorViewEngine选项时,需要ViewLocationExpander的对象,由于依赖性,无法创建该对象。
以下是代码
public MyViewLocationExpander(IOptions<MyAppSettings> MyAppSettings)
{
var appSettings = MyAppSettings.Value;
client = appSettings.Client // client is a private field and is used in ExpandViewLocations function
}
MyAppSettings.cs如下:
public class MyAppSettings
{
public string Client { get; set; }
}
在Startup.cs ConfigureServices方法
中services.Configure<RazorViewEngineOptions>(config =>
{
//config.ViewLocationExpanders.Add(new MyViewLocationExpander());
// MyViewLocationExpander cannot be created as it has a dependency on IOptions<MyAppSettings>
});
有关如何将自定义ViewLocationExpander添加到RazorViewEngineOptions的任何帮助都会很棒。
答案 0 :(得分:0)
从容器中解析服务的一种方法是在ExpandViewsMethod
中解析它们
using Microsoft.Extensions.DependencyInjection;
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
var service = context.ActionContext.HttpContext.RequestServices.GetService<IService>();
}