【发布时间】:2016-08-08 15:44:18
【问题描述】:
我正在将 Web 表单(不是 WebForm 技术,将 Web 应用程序剥离为 Web 表单功能)从 ASP.NET MVC 迁移到 ASP.NET Core MVC。我目前最大的问题是我们在以前版本的网络表单中拥有的静态类。此静态类使用 .NET 中可用但 .NET Core 中不可用的包。
我了解到对于这个静态类中的一些方法,我必须使用依赖注入来解决包问题。但是,无法将参数传递给静态类,使其成为 .NET Core 的“反模式”。
我的 Utils.cs 静态类只有两个方法,RenderPartialToString 和 SendEmail。 SendEmail 非常简单,对当前的 .NET Core 包没有任何问题。但是,我的静态类中有以下代码不适用于当前版本。
public static class Utils
{
public static readonly string ApiUrl = ConfigurationManager.AppSettings["ApiUrl"];
public static readonly string ApiKey = ConfigurationManager.AppSettings["ApiKey"];
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() + "');";
}
}
...
}
ViewEngine 和 ConfigurationManager 在 .NET Core 中不可用,使得这个静态类很难迁移。我相信,我可以通过依赖注入来实现这两个功能。但是,我不知道如何更改这个静态类,以便我可以使用依赖注入并能够在我的控制器中使用这些方法。
如何简单地将这个静态类迁移到 .NET Core 中以实现一些依赖注入?我是否需要更改 Utils 类的所有实例并使其不是静态的?
【问题讨论】:
-
呃什么? “从 ASP.NET MVC 到...的网络表单应用程序”? ASP.NET MVC 是一种不同于 ASP.NET(又名 WebForms)的技术
-
查看stackoverflow.com/questions/31905624/… 查看引擎部分。对于 ConfigurationManager,您需要
IOption<T>docs.asp.net/en/latest/fundamentals/configuration.html -
@Tseng 很抱歉没有澄清,它是一个使用 MVC(不是 WebForms)的精简 Web 应用程序。因此,它不是 WebForm 技术。
-
@Kalten 很好的链接,答案很好! :P
-
@Kalten 感谢 ViewEngine 的建议,但我已经尝试过了,stackoverflow.com/questions/38749745/… 我现在将研究 IOption
。
标签: c# asp.net .net asp.net-mvc asp.net-core