using System; using System.Collections.Generic; using System.Text; using System.Configuration; using System.Reflection; namespace ConsoleApplication1 { class TestFactoryFromAppConfig { /// <summary> /// 个性化实现工厂类DLL缓存 /// </summary> private static Dictionary<string, Assembly> _FactoryDllCach = new Dictionary<string, Assembly>(); public static void Main() { TestFactoryFromAppConfig tfac = new TestFactoryFromAppConfig(); Interface ife = (Interface)tfac.GetFactoryClass("SamTestForFactory"); ife.SayHello(); Console.Read(); } private object GetFactoryClass(string p) { /// <summary> /// 获取个性化实现工厂类 /// </summary> object actionObj = null; string vValue = ConfigurationManager.AppSettings[p]; string[] typeList = vValue.Split(','); try { System.Reflection.Assembly dll = null; if (_FactoryDllCach.ContainsKey(p)) { dll = _FactoryDllCach[p]; } else { dll = Assembly.Load(typeList[1].Trim()); _FactoryDllCach.Add(p, dll); } actionObj = dll.CreateInstance(typeList[0].Trim()); } catch (Exception ex) { throw new Exception("加载实现类出错!", ex); } return actionObj; } } }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1.ChildFolder { class Child : Interface { #region Interface 成员 public void SayHello() { string teacher = "teacher"; Console.WriteLine("hellow {0}", teacher); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { public interface Interface { void SayHello(); } }appconfig配置文件定义了一个键值对,通过 ConfigurationManager.AppSettings方法获取值。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="SamTestForFactory" value="ConsoleApplication1.ChildFolder.Child,ConsoleApplication1"/> </appSettings> </configuration>
把程序集放入缓存中,如果下次访问的仍然是同一个键,则无需再次装载程序集,从缓存中读取即可。