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);
                }

3.加載dll后如果要更新業務代碼,dll會被鎖定,無法替換,需要重啟應用

解決辦法是通過AppDomain對業務項目dll獨立加載,更新時進行卸載

1)創建一個RemoteLoader一個可穿越邊界的類,作為加載dll的一個包裝

 public class RemoteLoader : MarshalByRefObject
    {
        private Assembly assembly;

        public Assembly LoadAssembly(string fullName)
        {
            assembly = Assembly.LoadFile(fullName);
            return assembly;
        }

        public string FullName
        {
            get { return assembly.FullName; }
        }

    }

2)創建LocalLoader作為AppDomian創建與卸載的載體

public class LocalLoader
    {
        private AppDomain appDomain;
        private RemoteLoader remoteLoader;
        private DirectoryInfo MainFolder;
        public LocalLoader()
        {

            AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
          
            setup.ShadowCopyDirectories = setup.ApplicationBase;
            appDomain = AppDomain.CreateDomain("PluginDomain", null, setup);

            string name = Assembly.GetExecutingAssembly().GetName().FullName;
            remoteLoader = (RemoteLoader)appDomain.CreateInstanceAndUnwrap(
                name,
                typeof(RemoteLoader).FullName);
        }

        public Assembly LoadAssembly(string fullName)
        {
            return remoteLoader.LoadAssembly(fullName);
        }

        public void Unload()
        {
            AppDomain.Unload(appDomain);
            appDomain = null;
        }

        public string FullName
        {
            get
            {
                return remoteLoader.FullName;
            }
        }
    }

這里需要說明的,AppDomainSetup配置文件請使用AppDomain.CurrentDomain.SetupInformation也就是使用框架的作用於配置信息,因為業務代碼會引用到很多框架的dll,如果獨立創建配置信息,會有找不到相關dll的錯誤,同時這里也需要配置web.confg文件指定額外的dll搜索目錄,因為業務工程代碼也會有很多層多個dll相互引用,不指定目錄也會存在找不到依賴dll的錯誤

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <!--插件加載目錄-->
      <probing privatePath="PluginTemp" />
    </assemblyBinding>
  </runtime>

3)創建業務代碼文件夾Plugin與臨時dll文件夾PluginTemp

為什么要創建臨時文件夾呢,因為我們需要在PluginTemp真正的加載dll,然后監聽Plugin文件夾的文件變化,有變化時進行AppDomain卸載這個操作,將Plugin中的dll拷貝到PluginTemp文件夾中,再重新加載dll

監聽Plugin文件夾:

private static readonly FileSystemWatcher _FileSystemWatcher = new FileSystemWatcher();
  public static void StartWatch()
        {
            _FileSystemWatcher.Path = HostingEnvironment.MapPath("~/Plugin");
            _FileSystemWatcher.Filter = "*.dll";
            _FileSystemWatcher.Changed += _fileSystemWatcher_Changed;

            _FileSystemWatcher.IncludeSubdirectories = true;
            _FileSystemWatcher.NotifyFilter =
                NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            _FileSystemWatcher.EnableRaisingEvents = true;
        }
        private static void _fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            DllList.Clear();
            Initialize(false);
            InjectUtil.InjectProject();
        }

拷貝dll:

 if (PluginLoader == null)
            {
                PluginLoader = new LocalLoader();
            }
            else
            {
                PluginLoader.Unload();
                PluginLoader = new LocalLoader();
            }

            TempPluginFolder.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            PluginFolder.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            //清理臨時文件。
            foreach (var file in TempPluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))
            {
                try
                {
                    File.SetAttributes(file.FullName, FileAttributes.Normal);
                    file.Delete();
                }
                catch (Exception)
                {
                    //這里雖然能成功刪除,但是會報沒有權限的異常,就不catch了
                }

            }
            //復制插件進臨時文件夾。
            foreach (var plugin in PluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))
            {
                try
                {
                    string CopyFilePath = Path.Combine(TempPluginFolder.FullName, plugin.Name);
                    File.Copy(plugin.FullName, CopyFilePath, true);
                    File.SetAttributes(CopyFilePath, FileAttributes.Normal);
                }
                catch (Exception)
                {
                    //這里雖然能成功刪除,但是會報沒有權限的異常,就不catch了
                }
            }

注:這里有個問題一直沒解決,就是刪除文件拷貝文件的時候,AppDomain已經卸載,但是始終提示無權限錯誤,但是操作又是成功的,暫時還未解決,如果大家有解決方法可以一起交流下

加載dll:

  public static IEnumerable<Assembly> GetProjectAssemblies()
        {
            if (DllList.Count==0)
            {
                IEnumerable<Assembly> assemblies = TempPluginFolder.GetFiles("*.dll", SearchOption.AllDirectories).Select(x => PluginLoader.LoadAssembly(x.FullName));
                foreach (Assembly item in assemblies)
                {
                    DllList.Add(item);
                }
            }
            return DllList;
        }

4.業務代碼的cshtml頁面如何加入到框架中被訪問

在MVC工程中,cshtml也是需要被編譯的,我們可以通過RazorBuildProvider將外部編譯的頁面動態加載進去

 public static void InitializeView()
        {
            IEnumerable<Assembly> assemblies = GetProjectAssemblies();
            foreach (var assembly in assemblies)
            {
                RazorBuildProvider.CodeGenerationStarted += (object sender, EventArgs e) =>
               {
                   RazorBuildProvider provider = (RazorBuildProvider)sender;
                   provider.AssemblyBuilder.AddAssemblyReference(assembly);
               };
            }

        }

RazorBuildProvider方法啊只是在路由層面將cshtml加入到框架中,我們還需要將業務工程View中模塊的頁面掛載虛擬目錄到框架中,如圖所示

5.框架啟動后,更新業務dll帶來的相關問題

在啟動的項目中我們更新dll,我們希望達到的效果是和更新框架bin目錄文件的dll一樣,程序會重啟,這樣就會再次調用被PreApplicationStartMethod注解標注的方法,不需要在代碼中做額外處理判斷是首次加載還是更新加載,同時也做不到動態的將外部dll加入到MVC編譯dll體系中,也只能啟動前加載,查了很多資料,重新加載項目可以通過代碼控制IIS回收程序池達到效果,但是因為各種繁瑣的權限配置問題而放棄,我最后的解決方法是比較歪門邪道的方法,更新web.config文件的修改日期,因為iis會監控配置文件,更新了會重啟引用,大家如果有更好的簡單的方法,可以評論回復我呦

//這里通過修改webconfig文件的時間達到重啟應用,加載項目dll的目的!
File.SetLastWriteTime(HostingEnvironment.MapPath("~/Web.config"), System.DateTime.Now);

博客園沒找到資源上傳地址,傳到碼雲上了,放個地址:https://gitee.com/code2roc/FastExecutor/attach_files


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM