我正在构建一个使用 MEF 的 MVC 3 应用程序。主要思想是具有插件机制,其中模型、控制器和视图在运行时从 mef 容器动态加载。
每个插件/模块由两个程序集组成:
- Module1.Data.dll(包含模型定义)
- Module1.Web.dll(包含控制器和视图)
并放在 Web 应用程序 bin 内的 Plugins 目录中:
- WebApp/Bin/Plugins/Module1.Data.dll
- WebApp/Bin/Plugins/Module1.Web.dll
- WebApp/Bin/Plugins/Module2.Data.dll
- WebApp/Bin/插件/Module2.Web.dll
- WebApp/Bin/Plugins/ModuleCore.Data.dll
- WebApp/Bin/Plugins/ModuleCore.Web.dll
- ETC...
还有一个核心模块被所有其他模块引用:ModuleCore.Data.dll 和 ModuleCore.Web.dll。
然后,在 Global.asax 中,容器按以下方式构建:
AggregateCatalog catalog = new AggregateCatalog();
var binCatalog = new DirectoryCatalog(HttpRuntime.BinDirectory, "Module*.dll");
var pluginsCatalot = new DirectoryCatalog(Path.Combine(HttpRuntime.BinDirectory, "Plugins"), "Module*.dll");
catalog.Catalogs.Add(binCatalog);
catalog.Catalogs.Add(pluginsCatalot);
CompositionContainer container = new CompositionContainer(catalog);
container.ComposeParts(this);
AppDomain.CurrentDomain.AppendPrivatePath(Path.Combine(HttpRuntime.BinDirectory, "Plugins"));
CustomViewEngine 被创建并注册并用于在模块组装中查找视图:
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
用于从容器加载控制器的控制器工厂:
ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory(_container));
以及用于从容器获取程序集的自定义虚拟路径提供程序:
HostingEnvironment.RegisterVirtualPathProvider(new ModuleVirtualPathProvider());
好的,处理可插拔模型、控制器和视图的整个基础设施都准备好了。现在一切正常......除了一件事 -强类型视图。
为了更详细地说明问题,让我们准备场景:
- UserDTO 模型位于 Module1.Data.dll
- ShowUserController.cs 位于 Module1.Web.dll/Controllers/
- Index.cshtml 位于 Module1.Web.dll/Views/ShowUser (声明@model Module1.Data.UserDto)
现在我们执行以下操作:
- 运行应用程序并转到 HOST/ShowUser/Index(在 ShowUserController 上执行操作方法 Index 并获取视图 Index.cshtml)
- 获取视图 Index.cshtml 后 - 编译开始(通过 RazorBuildProvider)
- 抛出异常:“在命名空间 Module1 中找不到数据类型”,换句话说,在动态构建视图期间找不到 UserDTO
因此,编译器/构建器似乎没有查看 Module1.Data.dll 的 bin/Plugins 文件夹,因为当我将此文件复制到 bin 文件夹时 - 它的措辞很好。
问题/问题:为什么构建器没有查看 bin/Plugins 文件夹,即使此目录是由 AppDomain.CurrentDomain.AppendPrivatePath 方法添加的?如何为程序集生成器添加一次私有路径,以便将插件文件夹考虑在内?
我已经设法通过创建覆盖标准的 CustomRazorBuildProvider 来解决一些问题:
public class CustomRazorBuildProvider : RazorBuildProvider
{
public override void GenerateCode(System.Web.Compilation.AssemblyBuilder assemblyBuilder)
{
Assembly a = Assembly.LoadFrom(Path.Combine(HttpRuntime.BinDirectory, "Plugins", "Module1.Data.dll"));
assemblyBuilder.AddAssemblyReference(a);
base.GenerateCode(assemblyBuilder);
}
}
但是这种解决方案的缺点是每次编译视图时,都需要添加对Plugins文件夹中所有程序集的引用,这可能会在以后使用大量插件时导致性能问题。
有更好的解决方案吗?