6

我有一个大型 MVC 4 站点,每个 MVC 区域分为一个项目。我们使用 RazorGenerator 将我们所有的视图预编译到项目程序集中以进行部署,并将PrecompiledMvcEngine.ViewEngine

我刚刚创建了一个新区域,我想共享Shared来自另一个程序集的视图,但是InvalidOperationException当我试图定位一个局部视图时,我得到一个显示模板或编辑器模板似乎也找不到。

我相信它类似于这个问题中描述的问题

我在 RazorGenerator App_Start 中的代码是这样的:

var assemblies = new List<Tuple<string, Assembly>>()
{
    Tuple.Create("Areas/Area1", typeof(ABC.Project1.AreaRegistration).Assembly),
    Tuple.Create("Areas/Area2", typeof(ABC.Project2.AreaRegistration).Assembly),
};

// Get rid of the default view engine
ViewEngines.Engines.Clear();

foreach ( var assembly in assemblies )
{
    var engine = new PrecompiledMvcEngine(assembly.Item2, assembly.Item1) {
        UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
    };

    // Allow sharing of Area1 Shares views with Area2
    if (assembly.Item1 == "Areas/Area2")
    {
        var sharedPaths = new[] { "~/Areas/Area1/Views/Shared/{0}.cshtml" };

        engine.ViewLocationFormats = engine.ViewLocationFormats.Concat(sharedPaths).ToArray();
        engine.MasterLocationFormats = engine.MasterLocationFormats.Concat(sharedPaths).ToArray();
        engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Concat(sharedPaths).ToArray();
    }

    ViewEngines.Engines.Insert(0, engine);

    VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
}

当我在 Area2 之类的视图中遇到部分引用时@Html.Partial("Partials/Footer"),我得到了异常。看来 Razor 正在寻找正确的路径

System.InvalidOperationException: The partial view 'Partials/Footer' was not found or no view engine supports the searched locations. The following locations were searched:
    ~/Areas/Area2/Views/Home/Partials/Footer.cshtml
    ~/Areas/Area2/Views/Shared/Partials/Footer.cshtml
    ~/Views/Home/Partials/Footer.cshtml
    ~/Views/Shared/Partials/Footer.cshtml
    ~/Areas/Area1/Views/Shared/Partials/Footer.cshtml
at System.Web.Mvc.HtmlHelper.FindPartialView(ViewContext viewContext, String partialViewName, ViewEngineCollection viewEngineCollection)

查看 的源代码PrecompiledMvcEngine,它似乎只在程序集中查找视图。

我最初认为视图系统在尝试解析路径时会查看所有已注册的 ViewEngines,但这似乎是一个不正确的假设(我可以理解为什么不这样做)。

有没有办法在多个程序集中共享视图?

更新

我通过创建一个自定义版本来解决这个问题,该版本PrecompiledMvcEngine在其构造函数中采用程序集列表。核心变化是这样的:

_mappings = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

foreach (var kvp in assemblies)
{
    var baseVirtualPath = NormalizeBaseVirtualPath(kvp.Key);
    var assembly = kvp.Value;

    var mapping = from type in assembly.GetTypes()
        where typeof(WebPageRenderingBase).IsAssignableFrom(type)
        let pageVirtualPath = type.GetCustomAttributes(inherit: false).OfType<PageVirtualPathAttribute>().FirstOrDefault()
        where pageVirtualPath != null
        select new KeyValuePair<string, Type>(CombineVirtualPaths(baseVirtualPath, pageVirtualPath.VirtualPath), type);

    foreach (var map in mapping)
    {
        _mappings.Add(map);
    }
}

这种方法有更好的选择或陷阱吗?

4

0 回答 0