FileSystemEventArgs e){DllList.Clear();Initialize( false );
标签:
原文:ASP.NET MVC模块化开发——动态挂载外部项目比来在开发一个MVC框架,开发过程中考虑到以后开发依托于框架的项目,为了框架的维护更新升级,代码必定要和具体的业务工程支解开来,所以需要解决业务工程挂载在框架工程的问题,MVC与传统的ASP.NET差别,WebForm项目只需要挂在虚拟目录拷贝dll就可以访谒,但是MVC不成能去引用工程项目的dll从头编译,从而孕育产生了开发一个动态挂在MVC项目成果的想法,MVC项目挂载主要有几个问题,接下来进行详细的分析与完成解决方案
一般动态加载dll的要领是使用Assembly.LoadFIle的要领来挪用,但是会存在如下问题:
1.如果MVC项目中存在依赖注入,框架层面无法将外部dll的类放入IOC容器通过 BuildManager.AddReferencedAssembly要领在MVC项目启动前,动态将外部代码添加到项目的编译体系中,需要共同PreApplicationStartMethod注解使用,示例:
声明一个类,然后进行注解符号,指定MVC启动前要领
//使用PreApplicationStartMethod注解的感化是在mvc应用启动之前执行操纵 [assembly: PreApplicationStartMethod(typeof(FastExecutor.Base.Util.PluginUtil), "PreInitialize")] namespace FastExecutor.Base.Util { public class PluginUtil { public static void PreInitialize() { } } } 2.外部加载的dll中的Controller无法被识别通过自界说的ControllerFactory重写GetControllerType要领进行识别
public class FastControllerFactory : DefaultControllerFactory { protected override Type GetControllerType(RequestContext requestContext, string controllerName) { Type ControllerType = PluginUtil.GetControllerType(controllerName + "Controller"); if (ControllerType == null) { ControllerType = base.GetControllerType(requestContext, controllerName); } return ControllerType; } }
在Global.asax文件中进行ControllerFactory的替换
ControllerBuilder.Current.SetControllerFactory(new FastControllerFactory());
ControllerTypeDic是遍历外部dll获取到的所有Controller,这里需要考虑到Controller通过RoutePrefix注解自界说Controller前缀的情况
IEnumerable<Assembly> assemblies = GetProjectAssemblies(); foreach (var assembly in assemblies) { foreach (var type in assembly.GetTypes()) { if (type.GetInterface(typeof(IController).Name) != null && type.Name.Contains("Controller") && type.IsClass && !type.IsAbstract) { string Name = type.Name; //如果有自界说的路由注解 if (type.IsDefined(typeof(System.Web.Mvc.RoutePrefixAttribute), false)) { var rounteattribute = type.GetCustomAttributes(typeof(System.Web.Mvc.RoutePrefixAttribute), false).FirstOrDefault(); Name = ((System.Web.Mvc.RoutePrefixAttribute)rounteattribute).Prefix + "Controller"; } if (!ControllerTypeDic.ContainsKey(Name)) { ControllerTypeDic.Add(Name, type); } } } BuildManager.AddReferencedAssembly(assembly); }
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32946.html