NetCore插件化開發

使用NetCore3.1完成框架基本開發後實際應用於項目,須要保證框架的獨立性與項目的個性化, 就須要相似於下圖的插件化形式將項目放入框架這個容器中啓動,下面開始詳細介紹實現步驟html

項目dll掃描

在框架根目錄建立Plugin文件夾,項目在生成後事件使用copy命令拷貝至Plugin文件夾,框架啓動時會掃描該文件夾並進行ShadowCopy到PluginTemplate文件夾中app

   private static void ScanPlugin()
        {
            if (!PluginFolder.Exists)
            {
                PluginFolder.Create();
            }
            if (!TempPluginFolder.Exists)
            {
                TempPluginFolder.Create();
            }

            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 e)
                {
                    throw new Exception("請檢查IIS權限");
                }

            }
            //複製插件進臨時文件夾。
            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 e)
                {
                    throw new Exception("請檢查IIS權限");
                }
            }
        }

項目dll加載

直接使用ApplicationParts加載AssemblyPart便可框架

     public static void LoadPlugin()
        {
            ScanPlugin();
            IEnumerable<Assembly> AssemblyList = GetPluginAssemblies();
            foreach (Assembly assembly in AssemblyList)
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.IsAssignableFrom(typeof(Controller)) && type.Name.Contains("Controller") && type.IsClass && !type.IsAbstract)
                    {
                        string Name = type.Name;
                        //若是有自定義的路由註解
                        if (type.IsDefined(typeof(Route), false))
                        {
                            var areaattribute = type.GetCustomAttributes(typeof(Route), false).FirstOrDefault();
                            Name = ((Route)areaattribute).Name;
                            Name += "Controller";

                        }
                        if (!ControllerTypeDic.ContainsKey(Name))
                        {
                            ControllerTypeDic.Add(Name, type);
                        }
                    }
                }
                var controllerAssemblyPart = new AssemblyPart(assembly);
                CloudUtil.GetBuilder().ConfigureApplicationPartManager(apm =>
                {
                    apm.ApplicationParts.Add(controllerAssemblyPart);
                });
            }
            CloudUtil.GetBuilder().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            StartPluginRefreshWatch();
        }

項目視圖

項目的cshtml視圖文件能夠手動拷貝到部署的框架Views文件夾中(正式環境),也能夠經過監控當前項目的Views文件夾,若是變更進行自動拷貝(開發環境)ui

  private static void StartPluginRefreshWatch()
        {
            _FileSystemWatcher.Path = CloudUtil.GetContentPath() + "/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;

            if (AppConfigUtil.Configuration["Frame:ViewsPublishType"]=="AutoCopy"
                && !string.IsNullOrEmpty(AppConfigUtil.Configuration["Frame:ViewsVirtualPath"]) 
                && Directory.Exists(AppConfigUtil.Configuration["Frame:ViewsVirtualPath"]))
            {
                FileSystemWatcher ViewsWatcher = new FileSystemWatcher();
                ViewsWatcher.Path = AppConfigUtil.Configuration["Frame:ViewsVirtualPath"];
                ViewsWatcher.Changed += ViewsWatcher_Changed;

                ViewsWatcher.IncludeSubdirectories = true;
                ViewsWatcher.NotifyFilter =
                    NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
                ViewsWatcher.EnableRaisingEvents = true;

                //系統啓動時整個文件夾拷貝
                DirectoryInfo FrameWorkViews = new DirectoryInfo(CloudUtil.GetContentPath() + "/Views");
                DirectoryInfo ProjectViews = new DirectoryInfo(AppConfigUtil.Configuration["Frame:ViewsVirtualPath"]);
                foreach (DirectoryInfo FDir in FrameWorkViews.GetDirectories())
                {
                    foreach (DirectoryInfo PDir in ProjectViews.GetDirectories())
                    {
                        if (PDir.Name== FDir.Name)
                        {
                            FileUtil.DeleteDirectoryContent(FDir.FullName);
                        }
                    }
                }
                FileUtil.CopyDirectory(AppConfigUtil.Configuration["Frame:ViewsVirtualPath"],CloudUtil.GetContentPath() + "/Views", true);
            }
        }

項目dll熱更新

監控Plugin文件夾,如有變調用IApplicationLifetime的StopApplication重啓系統spa

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, Microsoft.AspNetCore.Hosting.IApplicationLifetime applicationLifetime)
 {
      CloudUtil.SetAPP(applicationLifetime);
 }


 private static void _FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
 {
      CloudUtil.Restrat();
 }

 public static void Restrat()
 {
      APP.StopApplication();
 }
相關文章
相關標籤/搜索