成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

如何用MEF實現(xiàn)Asp.NetMVC框架

目的是實現(xiàn)多個Controller類,View在不同的dll里, 供一個大框架調用。 

原理:
1.用MEF實現(xiàn)各個Controller類的dll的導出和導入。
2.用[PartCreationPolicy(CreationPolicy.NonShared)]標記來實現(xiàn)每個Controller在Export時重新創(chuàng)建實例
3.繼承DefaultControllerFactory來創(chuàng)建我們自定義的ControllerFactory。
4.用ControllerBuilder.Current.SetControllerFactory 調用我們創(chuàng)建的ControllerFactory類
5.繼承RazorViewEngine, 實現(xiàn)我們自定義的ViewEngine。
6.用ViewEngines.Engines.Clear();
     ViewEngines.Engines.Add(我們實現(xiàn)的自定義ViewEngine); 
 7.繼承VirtualPathProvider和VirtualFile實現(xiàn)我們自定義的VirtualPath, 來查找各個子模塊的資源(View)
8.用System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(我們自定義的VirtualPathProvider);
 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.框架層的實現(xiàn): 
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)         {         }           protectedoverridevoidRenderView(ViewContextviewContext,TextWriterwriter,objectinstance)
         {             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>
            

網頁標題:如何用MEF實現(xiàn)Asp.NetMVC框架
瀏覽地址:http://jinyejixie.com/article24/iehcje.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供微信小程序、ChatGPT、全網營銷推廣網站內鏈、靜態(tài)網站、軟件開發(fā)

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

網站優(yōu)化排名
长顺县| 金华市| 庆阳市| 武穴市| 自贡市| 琼海市| 自贡市| 昌乐县| 屏边| 伊春市| 平陆县| 丹棱县| 松滋市| 昌黎县| 南江县| 昌平区| 淮南市| 那坡县| 平乡县| 湘乡市| 宜兰市| 闵行区| 南京市| 栖霞市| 远安县| 团风县| 宁阳县| 新蔡县| 上思县| 十堰市| 永泰县| 台州市| 同江市| 武山县| 启东市| 扎赉特旗| 宁安市| 洪洞县| 左云县| 香港 | 蒙阴县|