如何用MEF实现Asp.Net MVC框架

2024-04-01 22:35:45
<?xml version="1.0" encoding="UTF-8"?> 目的是实现多个Controller类,View在不同的dll里, 供一个大框架调用。

原理:
1.用MEF实现各个Controller类的dll的导出和导入。
2.用[PartCreationPolicy(CreationPolicy.NonShared)]标记来实现每个Controller在Export时重新创建实例
3.继承DefaultControllerFactory来创建我们自定义的ControllerFactory。
4.用ControllerBuilder.Current.SetControllerFactory 调用我们创建的ControllerFactory类
5.继承RazorViewEngine, 实现我们自定义的ViewEngine。
6.用ViewEngines.Engines.Clear();
     ViewEngines.Engines.Add(); 
 7.继承VirtualPathProviderVirtualFile实现我们自定义的VirtualPath, 来查找各个子模块的资源(View)
8.用System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(); 
 9.子模块中的改变,1:每个View的属性设置为Embedded Resource, 每个Controller类有Export和PartCreationPolicy属性。


 1.     修改Controller类:继承IPACSModule,添加[PartCreationPolicy(CreationPolicy.NonShared)]标签[PartCreationPolicy(CreationPolicy.NonShared)]public class PatientAdminController : Controller,IPACSModule

2.     修改View的属性Build Action为Embedder Resource

3.     修改XXXX.Cshtml, 添加@inherits System.Web.Mvc.WebViewPage, 如果Cshtml中有@model, 如:@model  IEnumerable<UIH.PACS.Workstation.PatientAdmin.Models.OrderViewModel>改为

@using System.Web.WebPages;    @using System.Web.Mvc;    @using System.Web.Mvc.Ajax;    @using System.Web.Mvc.Html;    @using System.Web.Routing;  

@inherits System.Web.Mvc.WebViewPage<IEnumerable<UIH.PACS.Workstation.PatientAdmin.Models.OrderViewModel>>@using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "main" })){}

 具体代码: 
 1.框架层的实现: 

using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Caching; using System.Web.Hosting; using System.Web.Mvc; using System.Web.WebPages; using UIH.PACS.Workstation.AddIn.Interface; using System.Globalization; using System.ComponentModel.Composition.Primitives;   namespace UIH.PACS.Workstation.Common {     public class ExtensionHelper     {         [ImportMany(AllowRecomposition = true)]         public IEnumerable<IPACSModule> PACSModules { get; set; }           public CompositionContainer _container;           public void Initialize()         {             AggregateCatalog catalog = new AggregateCatalog();               catalog.Catalogs.Add(new AggregateCatalog(                 new DirectoryCatalog(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")),                 new AssemblyCatalog(typeof(Controller).Assembly),                 new TypeCatalog(typeof(IPACSModule))                 ));               _container = new CompositionContainer(catalog);               try             {                 _container.ComposeParts(this);             }             catch (CompositionException ex)             {                 throw new SystemException(ex.Message, ex);             }               //Set Custom Controller             ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());               //Set Custom ViewEngine             ViewEngines.Engines.Clear();             ViewEngines.Engines.Add(new CustomViewEngine());               //Register a virtual path provider             System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new CustomVirtualPathProvider());                 }     }       public class CustomControllerFactory : DefaultControllerFactory      {         protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)         {             //{call AddIn controller             var export = MvcApplication._extHelper._container.GetExports<IPACSModule>()                 .Where(e => e.Value.GetType().Equals(controllerType))                 .FirstOrDefault();               if (null != export)             {                 return export.Value as Controller;             }             else             {                 return base.GetControllerInstance(requestContext, controllerType);             }             //end AddIn controller}         }           public override void ReleaseController(IController controller)         {             IDisposable disposable = controller as IDisposable;             if (disposable != null)             {                 disposable.Dispose();             }                //base.ReleaseController(controller);         }     }       public class CustomViewEngine : RazorViewEngine     {         public CustomViewEngine()         {             base.AreaViewLocationFormats = new string[]              { "~/Areas/{2}/Views/{1}/{0}.cshtml",                  "~/Areas/{2}/Views/Shared/{0}.cshtml"};               base.AreaMasterLocationFormats = new string[]              { "~/Areas/{2}/Views/{1}/{0}.cshtml",                  "~/Areas/{2}/Views/Shared/{0}.cshtml" };               base.AreaPartialViewLocationFormats = new string[]              { "~/Areas/{2}/Views/{1}/{0}.cshtml",                 "~/Areas/{2}/Views/Shared/{0}.cshtml" };               base.ViewLocationFormats = new string[]              { "~/Views/{1}/{0}.cshtml",                 "~/Views/Shared/{0}.cshtml",                 "~/PACSModule/Views/{1}/{0}.cshtml",                 "~/PACSModule/Views/Shared/{0}.cshtml"};               base.MasterLocationFormats = new string[]              { "~/Views/{1}/{0}.cshtml",                 "~/Views/Shared/{0}.cshtml",                  "~/PACSModule/Views/{1}/{0}.cshtml",                  "~/PACSModule/Views/Shared/{0}.cshtml",                  "~/PACSModule/Views/{0}.cshtml"};               base.PartialViewLocationFormats = new string[]             { "~/Views/{1}/{0}.cshtml",                  "~/Views/Shared/{0}.cshtml",                  "~/PACSModule/Views/{1}/{0}.cshtml",                 "~/PACSModule/Views/Shared/{0}.cshtml",                 "~/PACSModule/Views/{0}.cshtml"};               base.FileExtensions = new string[] { "cshtml"};         }           protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)         {             var dllName = controllerContext.Controller.GetType().Module.Name;               return base.CreatePartialView(controllerContext, partialPath.Replace("PACSModule", dllName));         }           protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)         {             var dllName = controllerContext.Controller.GetType().Module.Name;               RazorView razorView = new RazorView(controllerContext, viewPath.Replace("PACSModule", dllName), masterPath, false, base.FileExtensions, base.ViewPageActivator);                 return razorView;         }           protected override bool FileExists(ControllerContext controllerContext, string virtualPath)         {             var dllName = controllerContext.Controller.GetType().Module.Name;               try             {                     return base.FileExists(controllerContext, virtualPath.Replace("PACSModule", dllName));                }             catch (System.Exception ex)             {                 return false;             }                       }     }       public class CustomView : RazorView     {         public CustomView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions, IViewPageActivator viewPageActivator)             : base(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, viewPageActivator)         {         }           protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
         {             if (writer == null)             {                 throw new ArgumentNullException("writer");             }               WebViewPage layoutPath = instance as WebViewPage;             if (layoutPath == null)             {                 throw new InvalidOperationException("WebViewPage is null.");             }               layoutPath.VirtualPath = this.ViewPath;             layoutPath.ViewContext = viewContext;             layoutPath.ViewData = viewContext.ViewData;             layoutPath.InitHelpers();               WebPageRenderingBase viewStartPage = null;             if (this.RunViewStartPages)             {                 try                 {                     viewStartPage = StartPage.GetStartPage(layoutPath, "_ViewStart", new string[] { "cshtml" });                 }                 catch                 {                     viewStartPage = GetStartPage(layoutPath, "~/Views/_ViewStart.cshtml");                 }             }               WebPageContext pageContext = new WebPageContext(null, null, null);             layoutPath.ExecutePageHierarchy(pageContext, writer, viewStartPage);         }           private static StartPage GetStartPage(WebViewPage childPage, string startPagePath)         {             StartPage startPage = null;               startPage = childPage.VirtualPathFactory.CreateInstance(startPagePath) as StartPage;             startPage.VirtualPath = startPagePath;             startPage.ChildPage = childPage;             startPage.VirtualPathFactory = childPage.VirtualPathFactory;               return startPage;         } 
     }       public class CustomVirtualPathProvider : VirtualPathProvider     {         private bool IsAppResourcePath(string virtualPath)         {             String checkPath = VirtualPathUtility.ToAppRelative(virtualPath);               return checkPath.StartsWith("~/UIH", StringComparison.InvariantCultureIgnoreCase);         }           public override bool FileExists(string virtualPath)         {             return (IsAppResourcePath(virtualPath) || base.FileExists(virtualPath));         }           public override VirtualFile GetFile(string virtualPath)         {             if (IsAppResourcePath(virtualPath))             {                 return new CustomVirtualFile(virtualPath);             }             else             {                 return base.GetFile(virtualPath);             }         }           public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)         {             if (IsAppResourcePath(virtualPath))             {                 string[] parts = virtualPath.Split('/');                 string assemblyName = parts[1];                   Assembly asm = Assembly.Load(assemblyName.Replace(".DLL", "").Replace(".dll", ""));                 return new CacheDependency(asm.Location);             }             else             {                 return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);             }         }     }       public class CustomVirtualFile : VirtualFile     {         private string _virtualPath = "";           public CustomVirtualFile(string virtualPath)             : base(virtualPath)         {             _virtualPath = VirtualPathUtility.ToAppRelative(virtualPath);         }           public override System.IO.Stream Open()         {             string[] parts = _virtualPath.Split('/');             string assemblyName = parts[1];             string resourceName = assemblyName.Replace(".DLL", "").Replace(".dll", "") + "."                  + parts[2] + "."                 + parts[3] + "."                  + parts[4]; //"UIH.PACS.Workstation.AddIn.Demo."+"Views." + "Controller." + "Action.cshtml"               assemblyName = Path.Combine(HttpRuntime.BinDirectory, assemblyName);               System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(assemblyName);             if (null != assembly)             {                 Stream resourceStream = assembly.GetManifestResourceStream(resourceName);                 return resourceStream;             }               return null;         }     } } 



 2.IPACSModule就是空接口, 用来各个子模块的controller的Export 

     [InheritedExport(typeof(IPACSModule))]     public interface IPACSModule     {       } 

 3.子模块的Controller使用 

  [PartCreationPolicy(CreationPolicy.NonShared)]     public class TestController : Controller, IPACSModule     {         //         // GET: /Test/           public ActionResult Index()         {             return View();         }       } 
 4. 子模块的View的使用 



@inheritsSystem.Web.Mvc.WebViewPage   @{     ViewBag.Title = "Demo/Test/Index.cshtml"; }   <div class="content-wrapper">         This is Demo's index view for Test </div>

转载于:https://blog.51cto.com/muzizongheng/1333055

如何用MEF实现Asp.Net MVC框架相关推荐

  1. Scott的ASP.net MVC框架系列文章之四:处理表单数据(2)

    前几周我发表了一系列文章介绍我们正在研究的ASP.NET MVC框架.ASP.NET MVC框架为你提供了一种新的开发Web应用程序的途径,这种途径可以让应用程序变得更加层次清晰,而且更加有利于对代码 ...

  2. [转自scott]ASP.NET MVC框架 (第二部分): URL路径选择

    英文原文地址:http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.as ...

  3. 搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架

    搭建你的Spring.Net+Nhibernate+Asp.Net Mvc 框架 学习网址哦: 很不错的 http://www.cnblogs.com/fly_dragon/archive/2010/ ...

  4. [导入]ASP.NET MVC框架开发系列课程(3):URL导向.zip(16.66 MB)

    讲座内容: ASP.NET MVC框架中一个关键特性就是基于URL的导向.本次课程将讲解URL Routing机制的使用. 课程讲师: 赵劼 MSDN特邀讲师 赵劼(网名"老赵". ...

  5. ASP.NET MVC 框架路线图更新 【转】

    [原文地址]ASP.NET MVC Framework Road-Map Update [原文发表日期] Tuesday, February 12, 2008 1:05 PM 去年的十二月份,作为AS ...

  6. [导入]ASP.NET MVC框架开发系列课程(2):一个简单的ASP.NET MVC应用程序.zip(13.70 MB)...

    讲座内容: 使用ASP.NET MVC框架进行开发与ASP.NET WebForms截然不同.本次课程将通过官方的示例程序简单了解一下ASP.NET MVC应用程序的结构与特点. 课程讲师: 赵劼 M ...

  7. ASP.NET - MVC框架及搭建教程

    一.MVC简介 MVC:Model-View-Controller(模型-视图-控制器),MVC是一种软件开发架构模式. 1.模型(Model) 模型对象是实现应用程序数据域逻辑的应用程序部件. 通常 ...

  8. BrnShop开源网上商城第二讲:ASP.NET MVC框架

    BrnShop开源网上商城第二讲:ASP.NET MVC框架 原文:BrnShop开源网上商城第二讲:ASP.NET MVC框架 在团队设计BrnShop的web项目之初,我们碰到了两个问题,第一个是 ...

  9. [导入]ASP.NET MVC框架开发系列课程(1):MVC模式与ASP.NET MVC框架概述.zip(8.80 MB)

    讲座内容: ASP.NET MVC框架是既ASP.NET WebForms后的又一种开发方式.它提供了一系列优秀特性,使ASP.NET开发人员拥有了另一个选择.本次课程将对MVC模式ASP.NET M ...

最新文章

  1. CSDN - 进程结束后new出的内存会回收吗?
  2. Spring整合ActiveMQ接收消息
  3. 【渝粤题库】陕西师范大学202801 中国古代文学(五) 作业
  4. lsass.exe 当试图更新密码时_“驱动人生”下载器木马再度更新-你应该注意什么?...
  5. ecshop 手机版的php代码在哪里,PHP 在ecshop上集成 手机网页支付_php
  6. 内存恶鬼drawRect - 谈画图功能的内存优化
  7. Struts2的声明式异常处理
  8. python classmethod static_【python】classmethod staticmethod 区别
  9. params 有什么用?
  10. 编译WINDOWS版FFmpeg:编译SDL
  11. 返回顶部的几种方法总结
  12. Listary Pro - 搜索、管理都挺好
  13. 二叉树的四种遍历算法
  14. 《未来世界的幸存者》:你会是未来世界的幸存者吗?
  15. win10没有realtek高清晰音频管理器_Win10如何让电脑睡眠不断网?电脑睡眠状态不断网继续下载的方法...
  16. 阿里巴巴字体库使用方法
  17. C++学习(七十二)英寸 厘米 像素 dpi 分辨率
  18. 关闭Windows Defender工具
  19. “大数据分析”和“数据分析”的区别与联系
  20. 记录自学编程的博客 -2019年

热门文章

  1. 解决 Electron 5.0 版本出现 require is not defined 的问题
  2. 异常 Failed to instantiate [java.util.List]: Specified class is an interface
  3. Sonar问题及解决方案汇总
  4. 绝对位置,但相对于父位置
  5. 在Java / Maven中处理“Xerces hell”?
  6. 如何在SQL Server VARCHAR / NVARCHAR字符串中插入换行符
  7. Spring通过静态方法factory-method或实例工厂factory-bean获取bean对象
  8. Android:登录保存回显用户信息或配置文件(sharedpreferences)
  9. gulp html页面路径,通过gulp-connect部署静态页面,html页面中include路径无法get!
  10. pythoninit_Python __init__.py文件的作用