位置: 编程技术 - 正文

应用框架的设计与实现.net平台--跨领域组件--服务工厂(应用框架的设计方法)

编辑:rootadmin

推荐整理分享应用框架的设计与实现.net平台--跨领域组件--服务工厂(应用框架的设计方法),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:应用框架的设计与实现pdf,应用框架设计网页,应用框架的设计方法,应用框架设计网页代码,应用框架设计网页,应用框架的设计方法,应用框架的设计与实现pdf,应用框架的设计与实现pdf,内容如对您有帮助,希望把文章链接给更多的朋友!

定义服务抽象服务构建工厂,使之能够实现实现服务工厂族,针对不同的部署环境进行支持

/// <summary> /// 服务构建工厂接口 /// </summary>public interface IServiceFactory:IDisposable{ /// <summary> /// 上下文环境 /// </summary> string Name { get; } /// <summary> /// 获取一个服务的实例 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <returns></returns> T GetService<T>() where T : class; /// <summary> /// 根据配置中对应的名称获取服务的实例 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <param name="name">服务名称</param> /// <returns>服务实例</returns> T GetService<T>(string name) where T : class;}

普通服务构建工厂,通过IOC容器,加载服务层组件:

应用框架的设计与实现.net平台--跨领域组件--服务工厂(应用框架的设计方法)

/// <summary> /// 服务构建工厂 /// </summary> public class ServiceFactory : IServiceFactory { private static Type __serviceAttributeType = typeof(System.ServiceModel.ServiceContractAttribute); private string _lifetime; private IUnityContainer contianer; static bool _loaded; static object _sync = new object(); string path; static Lazy<string> defaultFactoryName = new Lazy<string>(() => { var q = AgileConfiguration.Current.Services.Cast<ServiceElement>(); var item = q.FirstOrDefault(c => c.Assembly == "*"); if (item != null) return item.Factory; else return string.Empty; }); static string GetFactoryName<T>() { var q = AgileConfiguration.Current.Services.Cast<ServiceElement>(); string name = typeof(T).Name; string assembly = typeof(T).Module.Name; assembly = assembly.Substring(0, assembly.Length - 4); var e = q.FirstOrDefault(c => c.Type == name && c.Assembly == assembly); if (e == null) e = q.FirstOrDefault(c => c.Assembly == assembly && (c.Type == "*" || string.IsNullOrEmpty(c.Type))); if (e != null) return e.Factory; else return defaultFactoryName.Value; } static IServiceFactory GetInstance<T>() { string factoryName = GetFactoryName<T>(); if (string.IsNullOrEmpty(factoryName)) return Container.Current.Resolve<IServiceFactory>(); else return Container.Current.Resolve<IServiceFactory>(factoryName); } static ServiceFactory() { InitialFactories(); } static void InitialFactories() { var items = AgileConfiguration.Current.ServiceFactories; var policy = new InterceptionBehavior<PolicyInjectionBehavior>(); var intercptor = new Interceptor<TransparentProxyInterceptor>(); foreach (ServiceFactoryElement item in items) { if (item.Name == "*" && Container.Current.IsRegistered<IServiceFactory>()) Trace.TraceWarning("ServiceFactorytsevice factory " &#; item.Type &#; "has been ironed registed into container."); try { var type = Type.GetType(item.Type, true); if (item.Name != "*") { Container.Current.RegisterType(typeof(IServiceFactory), type, item.Name, GetLifetimeManager(item.Lifetime), new InjectionConstructor(item.Lifetime),policy,intercptor); } else { Container.Current.RegisterType(typeof(IServiceFactory), type, GetLifetimeManager(item.Lifetime), new InjectionConstructor(item.Lifetime), policy, intercptor); } } catch (Exception ex) { throw new InvalidOperationException("regist serivce factory error,make sure configration is correct" &#; item.Type, ex); //) "注册服务工厂错误,请确认配置的类型是否正确:"; } } if (!Container.Current.IsRegistered<IServiceFactory>()) Container.Current.RegisterInstance<IServiceFactory>(new ServiceFactory(string.Empty), new ContainerControlledLifetimeManager()); } /// <summary> /// /// </summary> /// <param name="lifetime"></param> public ServiceFactory(string lifetime) { _lifetime = lifetime; contianer = Container.Current; } void Initial() { if (contianer == null) throw new ObjectDisposedException("ServiceFactory"); if (!_loaded) { lock (_sync) { if (!_loaded) { path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; var dir = new DirectoryInfo(path); var files = dir.GetFiles("*.services.???"); foreach (var file in files) LoadAssemblyFromFile(file); } } _loaded = true; } } private void LoadAssemblyFromFile(FileInfo file) { if (file.Extension == ".dll" || file.Extension == ".exe") { try { Trace.TraceInformation("ServiceFactorytload assembly " &#; file.Name); var types = Assembly.LoadFile(file.FullName).GetTypes().Where(c => c.IsClass && !c.IsAbstract && c.IsPublic); foreach (var item in types) { RegistType(item); } } catch { Trace.TraceError("ServiceFactorytload assembly failed " &#; file.Name); } } } private static LifetimeManager GetLifetimeManager(string lifetime) { if (string.IsNullOrEmpty(lifetime)) lifetime = "default"; if (Container.Current.IsRegistered<LifetimeManager>(lifetime)) return Container.Current.Resolve<LifetimeManager>(lifetime); else return new Microsoft.Practices.Unity.PerResolveLifetimeManager(); } private void RegistType(Type type) { var interfaces = type.GetInterfaces(); var q = interfaces.Where(c => ValidateServiceInterface(c)); if (q.Count() == 0) { Trace.TraceWarning("ServiceFactorytcoud not find any service contract in type of " &#; type.FullName); return; } foreach (var item in q) { if (!this.contianer.IsRegistered(item)) this.contianer.RegisterType(item, type, GetLifetimeManager(_lifetime)); } } private static bool ValidateServiceInterface(Type type) { if (!type.IsInterface) return false; return type.GetCustomAttributes(__serviceAttributeType, false).Length > 0; } /// <summary> /// 获取类型T实例 /// </summary> /// <typeparam name="T">类型</typeparam> /// <returns>T 的实例</returns> public static T GetService<T>() where T : class {#if DEBUG if (!ValidateServiceInterface(typeof(T))) throw new ArgumentException("服务接口必须有ServiceContractAttribute标注");#endif //return GetInstance<T>().GetService<T>(); return GetService<T>(null); }#if License static RempLicense lic = new RempLicense();#endif /// <summary> /// 根据服务在容器中的配置名称从服务容器中获取服务实例 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <param name="name">服务的名称</param> /// <returns>T的实例</returns> public static T GetService<T>(string name) where T : class {#if DEBUG if (!ValidateServiceInterface(typeof(T))) throw new ArgumentException("服务接口必须有ServiceContractAttribute标注");#endif#if License if (System.Diagnostics.Debugger.IsAttached) throw new NotImplementedException(); if (System.Web.HttpContext.Current != null) lic.Validate(typeof(T));#endif //var serviceName = string.IsNullOrEmpty(name) ? typeof(T).Name : name; return GetInstance<T>().GetService<T>(name); } /// <summary> /// 创建一个工厂 /// </summary> /// <param name="name">工厂名称</param> /// <returns><see cref="IServiceFactory"/></returns> public static IServiceFactory CreateFactory(string name) { if (Container.Current.IsRegistered<IServiceFactory>(name)) return Container.Current.Resolve<IServiceFactory>(name); else return null; } #region IServiceFactory Members T IServiceFactory.GetService<T>() { Initial(); try { return this.contianer.Resolve<T>(); } catch (ResolutionFailedException rf) { throw new InvalidOperationException("构建服务对象错误,请确认'" &#; typeof(T).FullName &#; "'对应的实现Dll是否已经Copy到当前应用程序的bin目录或者运行目录:" &#; path, rf); } } T IServiceFactory.GetService<T>(string name) { Initial(); try { return this.contianer.Resolve<T>(name); } catch (ResolutionFailedException re) { throw new InvalidOperationException("构建服务对象错误,请确认名称为" &#; "name" &#; "的对象'" &#; typeof(T).FullName &#; "'对应的实现Dll是否已经Copy到当前应用程序的bin目录或者运行目录中,并且已经注册", re); } } #endregion void IDisposable.Dispose() { } /// <summary> /// /// </summary> public string Name { get { return "Default"; } } /// <summary> /// 销毁服务 /// </summary> /// <param name="obj"></param> public static void DestroyService(IDisposable obj) { DestroyService(obj, null); } internal static void DestroyService(IDisposable obj, IClientInstrumentationProvider instrumentation) { if (obj == null) return; var client = obj as System.ServiceModel.IClientChannel; if (client != null && client.State == System.ServiceModel.CommunicationState.Faulted) { client.Abort(); if (instrumentation != null) instrumentation.Faulted(); } else { if (instrumentation != null) instrumentation.Closed(); } obj.Dispose(); } }

WCF服务端,客户端服务工厂类,提供服务远程调用:

ublic class ServiceFactory : IServiceFactory { private static readonly IClientInstrumentationProvider _instrumentation; static ServiceFactory() { if (Container.Current.IsRegistered<LifetimeManager>()) { var lm = Container.Current.Resolve<LifetimeManager>(); Container.Current.RegisterType<ClientFactory>(lm); } else Container.Current.RegisterType<ClientFactory>(new ContainerControlledLifetimeManager()); if (Container.Current.IsRegistered<IClientInstrumentationProvider>()) { _instrumentation = Unity.GetClientInstrumentationProvider(); } } string _lifetime; IUnityContainer InnerContainer { get { var val = _manager.GetValue() as IUnityContainer; if (val == null) { val = new UnityContainer(); _manager.SetValue(val); } return val; } } static object _sync = new object(); LifetimeManager _manager ; public ServiceFactory(string lifetime) { _lifetime = lifetime;//container = _manager.ge _manager = GetLifetimeManager(); } public T GetService<T>() where T : class { return GetService<T>(string.Empty); } public T GetService<T>(string name) where T : class { if (InnerContainer == null) throw new ObjectDisposedException("ServiceFactory"); if (string.IsNullOrEmpty(name)) name = typeof(T).Name; var obj = default(T); lock (_sync) { if (InnerContainer.IsRegistered<T>(name)) { obj = InnerContainer.Resolve<T>(name); var channel = obj as IClientChannel; if (Validate(channel)) return obj; } } obj = GetChannel<T>(name); return obj; } private bool Validate(IClientChannel channel) { if (channel == null) return false; try { if (channel.State > CommunicationState.Opened) return false; } catch (ObjectDisposedException) { return false; } return true; } private T GetChannel<T>(string name) where T : class { var obj = default(T); lock (_sync) { if (InnerContainer.IsRegistered<T>(name)) obj = InnerContainer.Resolve<T>(name); var channel = obj as IClientChannel; if (Validate(channel)) return obj; var clientFactory = Container.Current.Resolve<ClientFactory>(); if (ClientConfigHelper.IsEndPointExist(name)) { obj = clientFactory.CreateClient<T>(name); } else { var config = ClientConfigHelper.GetConfig<T>(); var address = config.GetAddress<T>(); if (string.IsNullOrWhiteSpace(address)) throw new ArgumentNullException(string.Format("没有找到EndPoint '{0}'对应的配置,请确认EndPoint是否已经正确配置", typeof(T).FullName)); var binding = RuntimeUnity.GetDefeaultBinding(); obj = clientFactory.CreateClient<T>(binding, new EndpointAddress(address), config.IsBidirectional); } InnerContainer.RegisterInstance<T>(name, obj, GetLifetimeManager()); } return obj; } private LifetimeManager GetLifetimeManager() { //return new ChannelLifeTimeManager(); if (string.IsNullOrEmpty(_lifetime)) return new ChannelLifeTimeManager(); if (Container.Current.IsRegistered<LifetimeManager>(_lifetime)) return Container.Current.Resolve<LifetimeManager>(_lifetime); else return new Microsoft.Practices.Unity.PerResolveLifetimeManager(); } public void Dispose() { InnerContainer.Dispose(); } public static void StartService(string baseAdress, IServiceFilter filter, IEventListener listener, Action<ServiceHost> action, Action<Exception> error = null) { var packages = RuntimeUnity.GetServicePackages(baseAdress); foreach (var p in packages) { try { var runner = new RemoteServiceRunner(); runner.Load(p); var el = new EventListener(); el.Notify &#;= (o, e) => { if (e.Type == "error")error(e.Exception); }; runner.Run(listener ?? el, filter ?? ServiceFilter.Empty); } catch (System.ServiceModel.CommunicationException ce) { throw new NotSupportedException("请确认Net.Tcp Port Sharing Service等服务是否开启,以及服务器配置是否正确。", ce); } catch (Exception ex) { if (error != null) error(ex); } } } #region private methods #endregion public static void CloseService(IDisposable obj) { CloseService(obj, null); } internal static void CloseService(IDisposable obj, IClientInstrumentationProvider instrumentation) { if (instrumentation == null) instrumentation = _instrumentation; var client = obj as System.ServiceModel.IClientChannel; if (client == null) return; if (client.State == System.ServiceModel.CommunicationState.Faulted) { client.Abort(); if (instrumentation != null) instrumentation.Faulted(); } else { client.Close(); if (instrumentation != null) instrumentation.Closed(); } } public string Name { get { return "WCF"; } } public void Teardown() { var lf = _manager as ChannelLifeTimeManager; if (lf == null) return; else lf.TearDown(); } }

Unity中protobuf的使用方法 在移动手机游戏开发中,目前Unity3D已成为比较主流的开发技术。那么对于客户端服务器协议的打解包,我们有3中常用的处理方式:1、自定义结构体:

[置顶] Unity Editor Extensions – Custom Inspectors 转载请注明出处:

Unity3D【火星大战二】 火星大战(二)1、我机发射子弹,打中敌机,当敌机生命为零或飞出界面时消失,如图:2、用到碰撞检测技术,产生碰撞必须满足的两个条件:1、包

标签: 应用框架的设计方法

本文链接地址:https://www.jiuchutong.com/biancheng/375791.html 转载请保留说明!

上一篇:Unity3d 导出ios、android等移动平台阴影效果步骤(unity导出3d模型)

下一篇:Unity中protobuf的使用方法(unityproject)

  • 小规模附加税如何做帐
  • 酒类产品的税率
  • 其他应收款利息收入会计分录怎么写
  • 增值税开票内容货物及应税劳务服务名称都有哪些
  • 生产车间领用低值易耗品
  • 什么情况下增值税进项税额要转出
  • 多付银行承兑退回的会计分录怎么写?
  • 固定资产发票怎么入账
  • 个人账户转公司账户需要交税吗
  • 为什么有的单位没有住房公积金
  • 工资薪金支出税收金额怎么算
  • 运费抵扣增值税是什么意思
  • 一般纳税人花椒税率
  • 红字发票怎么申报?
  • 商业承兑汇票贴现转让
  • 分公司不独立核算怎么报税
  • 小规模减征额哪些项目
  • 净资产属于政府预算会计要素吗
  • 收到进项税额发票怎么处理
  • 本企业领用外购原材料进项税要转出吗
  • txt文档乱码怎么办
  • WIN10专业版永久激活
  • 基准收益率是
  • 跟a签订合同可以撤销吗
  • 手撕票怎么做会计分录
  • 公司资质办理费用
  • os x yosemite dp5下载地址 os x 10.10 dp5更新内容
  • redhat无法进入图形界面
  • 房地产开发公司组织架构
  • thinkphp框架介绍
  • pace框架
  • ts基础
  • php框架运行机制
  • 驾校属于什么行业分类类别
  • 基于Java+Springboot+vue在线版权登记管理系统设计实现
  • 残保金的计费依据
  • 账户利息怎么计算
  • 当月已入账可是未入账
  • 如何设置linux
  • js执行上下文的概念
  • 用vue-cli搭建项目
  • 6%税点是什么意思
  • 利息收入计入借方
  • 出口货物的报关时间为货物运抵海关
  • sql的应用
  • 企业转钱给个人
  • 财务软件在建立账套功能中提供了
  • 疫情期间提涨薪合适吗
  • 逃税是什么意思?
  • 开具发票后,如发生销售退回,通常有的两种处理方式是?
  • 暂估成本的账务处理分录
  • 入库单金额写错可以改吗
  • 过路费怎么抵扣进项税额报表怎么填
  • 留抵税额在账上没有,怎么办
  • 小规模收的专票以后能抵扣吗
  • mysql如何修改数据库名
  • mysql中字符串类型
  • win xp 添加网络打印机
  • linux 磁盘使用
  • solaris删除文件夹命令
  • win8怎么设置定时关机
  • win7 64位系统提示"Windows7不能识别网络打印机"的故障原因及解决方法
  • windows怎么右键
  • perl正则表达
  • .json()
  • android实现推送
  • python抓取网络数据
  • [置顶]游戏名:chivalry2
  • vue只适合做单页项目吗
  • Node.js中的事件循环是什么样的
  • angularjs1.5
  • unity保存项目
  • js时间戳转日期格式
  • jquery右键弹出菜单
  • 广东省地方税务局公告2017年第7号
  • 税务行政处罚一般程序和简易程序的区别
  • 税务局风险防控形成长远
  • 农产品进项税额核定扣除办法2019
  • 扬州税务学院住宿环境
  • 下列哪些表述是正确的( )
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设