Resolver或ServiceProvider使用ICompositeViewEngine所需的依赖项

本文关键字:依赖 ICompositeViewEngine ServiceProvider 使用 Resolver | 更新日期: 2023-09-27 17:59:57

我正试图在ASP.NET Core MVC中使用ICompositeViewEngine来替换System.Web.MVC中的ViewEngine,因为它在.NET Core中不再可用。在这个项目中,我通常试图将Web表单从ASP.NET迁移到ASP.NET Core。

我找到了以下解决方案:MVC 6 Controller中的ControllerContext和ViewEngines属性在哪里?我相信这可以解决我的问题。我还在github问题中发现了ServiceProvider的类似引擎创建:https://github.com/aspnet/Mvc/issues/3091

然而,我不确定我可能缺少什么依赖项或框架,因为我是.NET的新手

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;

我认为这可能与我的问题有关。

我的原始代码是:

    public static string RenderPartialToString(Controller controller, string viewName, object model)
    {
        controller.ViewData.Model = model;
        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return "document.write('" + sw.GetStringBuilder().Replace(''n', ' ').Replace(''r', ' ').Replace("'","'''").ToString() + "');";
        }
    }

现在我正在尝试使用以下任一项:

 var engine = Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
 var engine2 = IServiceProvider.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;

我能解决这个问题吗?有没有一种更简单的方法来替换.NET Core中的System.Web.Mvc ViewEngines?我需要什么来修复Resolver和/或ServiceProvider的"在当前上下文中不存在"错误?

谢谢。我希望我能够遵循问题指南。

编辑:请告诉我是否应该在我的代码中为这个问题添加任何其他内容。我目前正在阅读有关依赖注入的文章,以便更好地了解这种情况。

Resolver或ServiceProvider使用ICompositeViewEngine所需的依赖项

您基本上是在正确的轨道上。ASP.NET Core去掉了许多静态对象,因此不能执行Resolver.GetService之类的操作。Resolver不存在。相反,请使用依赖项注入系统。

如果您只需要从控制器访问ICompositeViewEngine,请将其注入构造函数:

public MyController(ICompositeViewEngine viewEngine)
{
    // save a reference to viewEngine
}

如果你想拥有一个处理Razor到字符串渲染的离散服务,你需要在启动时注册它:

public void ConfigureServices(IServiceCollection services)
{
    // (Other code...)
    services.AddTransient<IViewRenderingService, ViewRenderingService>();
    services.AddMvc();
}

服务本身看起来是这样的:

using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
public interface IViewRenderingService
{
    string RenderPartialView(ActionContext context, string name, object model = null);
}
public class ViewRenderingService : IViewRenderingService
{
    private readonly ICompositeViewEngine _viewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    public ViewRenderingService(ICompositeViewEngine viewEngine, ITempDataProvider tempDataProvider)
    {
        _viewEngine = viewEngine;
        _tempDataProvider = tempDataProvider;
    }
    public string RenderPartialView(ActionContext context, string name, object model)
    {
        var viewEngineResult = _viewEngine.FindView(context, name, false);
        if (!viewEngineResult.Success)
        {
            throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", name));
        }
        var view = viewEngineResult.View;
        using (var output = new StringWriter())
        {
            var viewContext = new ViewContext(
                context,
                view,
                new ViewDataDictionary(
                    new EmptyModelMetadataProvider(),
                    new ModelStateDictionary())
                {
                    Model = model
                },
                new TempDataDictionary(
                    context.HttpContext,
                    _tempDataProvider),
                output,
                new HtmlHelperOptions());
            view.RenderAsync(viewContext).GetAwaiter().GetResult();
            return output.ToString();
        }
    }
}

要从控制器使用它,请注入并调用它:

public class HomeController : Controller
{
    private readonly IViewRenderingService _viewRenderingService;
    public HomeController(IViewRenderingService viewRenderingService)
    {
        _viewRenderingService = viewRenderingService;
    }
    public IActionResult Index()
    {
        var result = _viewRenderingService.RenderPartialView(ControllerContext, "PartialViewName", model: null);
        // do something with the string
        return View();
    }
}

如果您想完全在MVC之外使用Razor,请参阅以下答案。