分享在winform下实现模块化插件编程-优化版
发布日期:2021-05-09 09:35:20 浏览次数:10 分类:博客文章

本文共 18408 字,大约阅读时间需要 61 分钟。

������������������������������������������������������������������������������������������������������

1.IAppContext������CreatePlugInForm���������������������������������������������formTypeName���������������������������������������������������������������������������������������������������������������AppFormTypes������������������������������������FORM������������������������

2.������������������������������������������������������������������������������������

3.���������������������LoadComponents������������������������������������������DLL���������������������������������������TYPE������������������������������ICompoentConfig������������������������������������������������

4.���������������������������������������������������DLL���������������������EXE������������

 ������������������������������������������������

1.���IAppContext������������CreatePlugInForm������������������������AppContext���������������������������������������

IAppContext���

///     /// ���������������������������������    /// ������������������������������������������������������������������������������������������������������������������������������������������������    /// ���������Zuowenjun    /// 2016-3-26    ///     public interface IAppContext    {        ///         /// ������������������        ///         string AppName { get; }        ///         /// ������������������        ///         string AppVersion { get; }        ///         /// ������������������        ///         object SessionUserInfo { get; }        ///         /// ������������������������        ///         object PermissionInfo { get; }        ///         /// ���������������������������������������������������������������������������������������������������        ///         ConcurrentDictionary
AppCache { get; } ///
/// ��������������������������������������������������������������������������������������� /// Form AppFormContainer { get; } ///
/// ��������������������������������������������������� /// ///
///
Form CreatePlugInForm(Type formType,params object[] args); ///
/// ��������������������������������������������������� /// ///
///
Form CreatePlugInForm(string formTypeName, params object[] args); ///
/// ��������������������������������������������������� /// ///
///
Form CreatePlugInForm
(params object[] args) where TForm : Form; }

AppContext���

///     /// ������������������������������    /// ���������Zuowenjun    /// 2016-3-26    ///     public class AppContext : IAppContext    {        internal static AppContext Current;        internal Dictionary
AppFormTypes { get; set; } public string AppName { get; private set; } public string AppVersion { get; private set; } public object SessionUserInfo { get; private set; } public object PermissionInfo { get; private set; } public ConcurrentDictionary
AppCache { get; private set; } public System.Windows.Forms.Form AppFormContainer { get; private set; } public AppContext(string appName, string appVersion, object sessionUserInfo, object permissionInfo, Form appFormContainer) { this.AppName = appName; this.AppVersion = appVersion; this.SessionUserInfo = sessionUserInfo; this.PermissionInfo = permissionInfo; this.AppCache = new ConcurrentDictionary
(); this.AppFormContainer = appFormContainer; } public System.Windows.Forms.Form CreatePlugInForm(Type formType, params object[] args) { if (this.AppFormTypes.ContainsValue(formType)) { return Activator.CreateInstance(formType, args) as Form; } else { throw new ArgumentOutOfRangeException(string.Format("���������������{0}������������������������������������������������������������", formType.FullName), "formType"); } } public System.Windows.Forms.Form CreatePlugInForm(string formTypeName, params object[] args) { if (!formTypeName.Contains('.')) { formTypeName = "." + formTypeName; } var formTypes = this.AppFormTypes.Where(t => t.Key.EndsWith(formTypeName, StringComparison.OrdinalIgnoreCase)).ToArray(); if (formTypes == null || formTypes.Length != 1) { throw new ArgumentException(string.Format("������������������������������������������������{0}���������������������������������!", formTypeName), "formTypeName"); } return CreatePlugInForm(formTypes[0].Value, args); } public Form CreatePlugInForm
(params object[] args) where TForm : Form { return CreatePlugInForm(typeof(TForm), args); } }

���AppContext���������������������CreatePlugInForm������������������������������������������TYPE������������������������������������������������������������������������������������������������������������������������args���������������������������

2.���Form���������������������������������������������SetPublicPropertyValue������������������������������������GetPublicPropertyValue���������������������������������������ExecutePublicMethod���������������������������������������������������������������������������������������������������������������������������������������������������

public static class FormExtension    {        ///         /// ���������������������������        ///         ///         ///         ///         public static void SetPublicPropertyValue(this Form form, string propertyName, object propertyValue)        {            var formType = form.GetType();            var property = formType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);            if (property != null)            {                property.SetValue(form, propertyValue, null);            }            else            {                throw new Exception(string.Format("������������������������{0}������������������������", propertyName));            }        }        ///         /// ������������������������������        ///         /// 
/// /// /// ///
public static TResult GetPublicPropertyValue
(this Form form, string propertyName, TResult defaultPropertyValue) { var formType = form.GetType(); var property = formType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); var proValue = property.GetValue(form, null); if (property != null) { try { return (TResult)Convert.ChangeType(proValue, typeof(TResult)); } catch { return defaultPropertyValue; } } else { throw new Exception(string.Format("������������������������{0}������������������������", propertyName)); } } ///
/// ��������������������������������������������������� /// ///
///
///
///
public static object ExecutePublicMethod(this Form form, string methodName, params object[] args) { var formType = form.GetType(); var method = formType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase); if (method != null) { return method.Invoke(form, args); } else { throw new Exception(string.Format("������������������������{0}���������������������{1}���������������������������", methodName, args == null ? 0 : args.Count())); } } }

������������������������������������������

3.���������������������������������������������������LoadComponents������������������������������������������ASP.NET ���Handler���Module������������������CONFIG������������������������������ASP.NET ���Handler���Module���������������������

���������������CONFIG������������������������������������������������������������������compoents���������������������������������������������appSettings������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������compoents���������������������

///     /// ���������������������    /// ���������Zuowenjun    /// 2016-3-30    ///     public class CompoentConfigurationSection : ConfigurationSection    {        private static readonly ConfigurationProperty s_property = new ConfigurationProperty(                string.Empty, typeof(ComponentCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]        public ComponentCollection Components        {            get            {                return (ComponentCollection)base[s_property];            }        }        [ConfigurationProperty("basePath", IsRequired = false)]        public string BasePath        {            get            {                return ReMapBasePath(this["basePath"].ToString());            }            set            {                this["basePath"] = ReMapBasePath(value);            }        }        private string ReMapBasePath(string basePath)        {            if (basePath.Trim().StartsWith("~\\"))            {                basePath = basePath.Replace("~\\", AppDomain.CurrentDomain.BaseDirectory + "\\");            }            return basePath;        }    }    ///     /// ���������������������    /// ���������Zuowenjun    /// 2016-3-30    ///     [ConfigurationCollection(typeof(ComponentElement))]    public class ComponentCollection : ConfigurationElementCollection    {        public ComponentCollection():base(StringComparer.OrdinalIgnoreCase)        {        }        protected override ConfigurationElement CreateNewElement()        {            return new ComponentElement();        }        protected override object GetElementKey(ConfigurationElement element)        {            return (element as ComponentElement).FileName;        }        new public ComponentElement this[string fileName]        {            get            {                return (ComponentElement)base.BaseGet(fileName);            }        }        public void Add(ComponentElement item)        {            this.BaseAdd(item);        }        public void Clear()        {            base.BaseClear();        }        public void Remove(string fileName)        {            base.BaseRemove(fileName);        }    }    ///     /// ������������������    /// ���������Zuowenjun    /// 2016-3-30    ///     public class ComponentElement : ConfigurationElement    {        [ConfigurationProperty("fileName", IsRequired = true, IsKey = true)]        public string FileName        {            get { return this["fileName"].ToString(); }            set { this["fileName"] = value; }        }        [ConfigurationProperty("entryType", IsRequired = true)]        public string EntryType        {            get { return this["entryType"].ToString(); }            set { this["entryType"] = value; }        }        [ConfigurationProperty("sortNo", IsRequired = false, DefaultValue = 0)]        public int SortNo        {            get { return Convert.ToInt32(this["sortNo"]); }            set { this["sortNo"] = value; }        }    }

������������������������������������

���������������������������������LoadComponents������������������������������

private void LoadComponents()        {            var compoents = ConfigurationManager.GetSection("compoents") as CompoentConfigurationSection;            if (compoents == null) return;            string basePath = compoents.BasePath;            if (string.IsNullOrWhiteSpace(basePath))            {                basePath = Program.AppLibsDir;            }            Type targetFormType = typeof(Form);            foreach (ComponentElement item in compoents.Components)            {                string filePath = Path.Combine(basePath, item.FileName);                var asy = Assembly.LoadFrom(filePath);                var type = asy.GetType(item.EntryType, true);                ICompoent compoent = null;                var config = (ICompoentConfig)Activator.CreateInstance(type);                config.CompoentRegister(AppContext.Current, out compoent);//������������������������������������������������compoent                if (compoent != null)                {                    foreach (Type formType in compoent.FormTypes)//������������������������������������AppContext���AppFormTypes���                    {                        if (targetFormType.IsAssignableFrom(formType) && !formType.IsAbstract)                        {                            AppContext.Current.AppFormTypes.Add(formType.FullName, formType);                        }                    }                }            }        }

���������������������LoadComponents������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

4.������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

������������������DLL������������������������������������Libs���������������������������������������������������������������������������������������������������������������������privatePath���������������������������������������������������������������������������������������������������������privatePath������������

������������������������������������������������AssemblyResolve������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

static class Program    {        public static string AppLibsDir = null;        ///         /// ������������������������������        ///         [STAThread]        static void Main(string[] args)        {            AppLibsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Libs\");            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;            AddEnvironmentPaths(AppLibsDir);        }        static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)        {            Assembly assembly = null, objExecutingAssemblies = null;            objExecutingAssemblies = Assembly.GetExecutingAssembly();            AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies();            foreach (AssemblyName assmblyName in arrReferencedAssmbNames)            {                if (assmblyName.FullName.Substring(0, assmblyName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))                {                    string path = System.IO.Path.Combine(AppLibsDir, args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll");                    assembly = Assembly.LoadFrom(path);                    break;                }            }            return assembly;        }        static void AddEnvironmentPaths(params string[] paths)        {            var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };            string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths));            Environment.SetEnvironmentVariable("PATH", newPath);        }    }

������������������������������������������������������AddEnvironmentPaths���������������������������������������������������[DllImport]���������������������������

������������������������������DLL������������������������:libs���������������������������������DLL���������������������������������False,������������������������������������������������������������

������������������������������������������������������������������������������������COPY������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������

������

 

上一篇:深入分析面向对象中的封装作用
下一篇:分享在winform下实现模块化插件编程

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月05日 01时41分46秒