C# 在视图位置扩展器中注入依赖项

C# 在视图位置扩展器中注入依赖项,c#,asp.net-mvc,dependency-injection,asp.net-core,C#,Asp.net Mvc,Dependency Injection,Asp.net Core,我在vnext项目中实现了自定义ViewLocationExpander。我想从ViewLocationExpander中的appsettings.json文件中读取应用程序设置值,因此IOptions已注入自定义ViewLocationExpander的构造函数中。但是,在将自定义ViewLocationExpander添加到RazorViewEngine选项时,需要ViewLocationExpander的对象,由于依赖关系,无法创建该对象 下面是代码 public MyViewLocati

我在vnext项目中实现了自定义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
}
在Startup.cs ConfigureServices方法中

services.Configure<RazorViewEngineOptions>(config =>
{
  //config.ViewLocationExpanders.Add(new MyViewLocationExpander());
  // MyViewLocationExpander cannot be created as it has a dependency on IOptions<MyAppSettings>
});
services.Configure(配置=>
{
//添加(新的MyViewLocationExpander());
//无法创建MyViewLocationExpander,因为它依赖于IOptions
});

有关如何将自定义ViewLocationExpander添加到RazorViewEngineOptions的任何帮助都将非常有用。

从容器解析服务的一种方法是在
ExpandViewsMethod

using Microsoft.Extensions.DependencyInjection;

public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
    var service = context.ActionContext.HttpContext.RequestServices.GetService<IService>();
}
使用Microsoft.Extensions.DependencyInjection;
公共IEnumerable ExpandViewLocations(ViewLocationExpanderContext上下文,IEnumerable viewLocations)
{
var service=context.ActionContext.HttpContext.RequestServices.GetService();
}

一种可能不太好的方法是让扩展器的构造函数接受IServiceCollection,然后传入“服务”,这将允许您检索选项我有两种方法来解决这个问题:1。我将“配置”传递给构造函数,并使用配置[“appSettingKey”]。2.我从ViewLocationExpander中删除了构造函数并访问了context.ActionContext.HttpContext.ApplicationServices.GetService(typeof(IOptions)),但在我看来,这些都是反模式的(不漂亮),因此可能有人能给出更好的解决方案。这里有一篇博客文章可能会给你一些想法,使用saaskit,他在一个视图扩展器中获得了一个租户实例,而没有太多令人讨厌的业务。我最终使用了上面评论中提到的选项2。在上面的博客链接中也使用了同样的方法。
using Microsoft.Extensions.DependencyInjection;

public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
    var service = context.ActionContext.HttpContext.RequestServices.GetService<IService>();
}