基于分层的接口开发,我们需要一个IOC 来管理,到处都 new对象显然是不明智的做法。虽然有很多第三方IOC框架,不过还是自己来实现一个简单的。
考虑到性能问题,不能每次都重新创建,需要一定的缓存技术。asp.net 中有一个缓存类System.Web.Caching.Cache,在winform或是wpf中也可以使用,但要引用System.Web.dll 这个dll是为web设计的,用来引用在桌面应用程序里面,似乎不太合适, 经过搜索,知道了微软在net 4 里面添加一个缓存类MemoryCache 类。它们都能监测文件的改变,所以改变ioc的配置文件都会实时生效。
我把IOC配置文件放在了App_Data目录下的一个自建xml文件,为什么放这个目录呢,因为默认情况下该目录不允许通过URL访问。先看看我博客怎么配置的
前面一个是接口,后面是接口的实现,这样如果想改变接口的实现只需要更改这个配置文件的后面一段。
IocHelper 类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Xml; namespace FYJ.Framework.Core { public class IocHelper where T : class { /// /// 获取一个实例 /// public static T Instance { get { string iocFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Ioc.xml"); ObjectCache cache = MemoryCache.Default; string fullName = typeof(T).FullName; if (cache[fullName] == null) { CacheItemPolicy policy = new CacheItemPolicy(); List filePaths = new List(); filePaths.Add(iocFilePath); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); T instace = Create(); cache.Set(fullName, instace, policy); } return cache[fullName] as T; } } /// /// 创建一个新实例 /// /// /// /// public static T Create() { string iocFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Ioc.xml"); string fullName = typeof(T).AssemblyQualifiedName; XmlDocument doc = new XmlDocument(); doc.Load(iocFilePath); foreach (XmlNode node in doc.GetElementsByTagName("Service")) { if (Type.GetType(node.Attributes["name"].InnerText).AssemblyQualifiedName == fullName) { Type instanceType = Type.GetType(node.Attributes["type"].InnerText); T o = (T)Activator.CreateInstance(instanceType); return o; } } return default(T); } } }