1.定义一个抽象类ServiceFactory,用来得到T接口的实现对象
public abstract class ServiceFactory { public abstract T CreateService<T>() where T : class; }
2.首先通过反射机制得到该interface的名字。得到该interface的实现实例后并缓存它。
/// <summary> /// 直接引用提供服务 /// </summary> public class RefServiceFactory : ServiceFactory { public override T CreateService<T>() { //第一次通过反射创建服务实例,然后缓存住 var interfaceName = typeof(T).Name; return CacheHelper.Get<T>(string.Format("Service_{0}", interfaceName), () => { return AssemblyHelper.FindTypeByInterface<T>(); }); } }
3.AssemblyHelper.FindTypeByInterface<T>();
该方法会在项目下的bin文件夹内查找dll文件,然后再去检测dll文件中的具体类
interfaceType.IsAssignableFrom(type) 判断type是否interfaceType的实现类
Activator.CreateInstance(type) 创建type类型的实例
/// <summary> /// 扫描程序集找到实现了某个接口的第一个实例 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="searchpattern">文件名过滤</param> /// <returns></returns> public static T FindTypeByInterface<T>(string searchpattern = "*.dll") where T : class { var interfaceType = typeof(T); string domain = GetBaseDirectory(); string[] dllFiles = Directory.GetFiles(domain, searchpattern, SearchOption.TopDirectoryOnly); foreach (string dllFileName in dllFiles) { foreach (Type type in Assembly.LoadFrom(dllFileName).GetLoadableTypes()) { if (interfaceType != type && interfaceType.IsAssignableFrom(type)) { var instance = Activator.CreateInstance(type) as T; return instance; } } } return null; } /// <summary> /// 得到当前应用程序的根目录 /// </summary> /// <returns></returns> public static string GetBaseDirectory() { var baseDirectory = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath == null) baseDirectory = AppDomain.CurrentDomain.BaseDirectory; return baseDirectory; }
时间: 2024-10-14 00:46:11