在Unity中,从Unity 取得的实例为 Transient。如果你希望使用多线程方式,就需要在组成时使用lifecycle参数,这时候取出的组件就不再是同一个了。在Unity IOC中,它支持我们对于组件的实例进行控制,也就是说我们可以透明的管理一个组件拥有多少个实例。Unity IOC容器提供了如下几种生命处理方式:

  • Singleton:一个组件只有一个实例被创建,所有请求的客户使用程序得到的都是同一个实例。
  • Transient:这种处理方式与我们平时使用new的效果是一样的,对于每次的请求得到的都是一个新的实例。
  • Custom:自定义的生命处理方式。

我要增加一个Request的,一个Request请求一个实例,然后在Request结束的时候,回收资源。 增加一个Resquest级别的LifetimeManager,HttpContext.Items中数据是Request期间共享数据用的,所以HttpContext.Items中放一个字典,用类型为key,类型的实例为value。如果当前Context.Items中有类型的实例,就直接返回实例。 ObjectContext本身是有缓存的,整个Request内都是一个ObjectContext,ObjectContext一级缓存能力进一步利用。

用在Unity中,如何获取对象的实例及如何销毁对象都是由LifetimeManager完成的,其定义如下

public abstract class LifetimeManager : ILifetimePolicy, IBuilderPolicy
{protected LifetimeManager();public abstract object GetValue();public abstract void RemoveValue();public abstract void SetValue(object newValue);
}

其中GetValue方法获取对象实例,RemoveValue方法销毁对象,SetValue方法为对外引用的保存提供新的实例

有了这3个方法,就可以通过自定义LifetimeManager来实现从HttpContext中取值。

下面我们来实现Unity集成ADO.NET Entity Framework的工作:

1、利用Unity的依赖注入,ObjectContext会给我们生成3个构造函数,类似于下面的代码:

// Original file name:
// Generation date: 2008/8/24 10:05:33
namespace RequestLifeTimeManagerTest
{using Microsoft.Practices.Unity;/// <summary>/// There are no comments for AdventureWorksLTEntities in the schema./// </summary>public partial class AdventureWorksLTEntities : global::System.Data.Objects.ObjectContext{/// <summary>/// Initializes a new AdventureWorksLTEntities object using the connection string found in the 'AdventureWorksLTEntities' section of the application configuration file./// </summary>public AdventureWorksLTEntities() : base("name=AdventureWorksLTEntities", "AdventureWorksLTEntities"){this.OnContextCreated();}/// <summary>/// Initialize a new AdventureWorksLTEntities object./// </summary>public AdventureWorksLTEntities(string connectionString) : base(connectionString, "AdventureWorksLTEntities"){this.OnContextCreated();}/// <summary>/// Initialize a new AdventureWorksLTEntities object./// </summary>public AdventureWorksLTEntities(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "AdventureWorksLTEntities"){this.OnContextCreated();}partial void OnContextCreated();……}构造函数注入包含了二种情况,一种是类仅有一个构造函数时,Unity 可以进行自动注入;另一种情况是,类包含多个构造函数时,必须使用 Attribute 或者配置文件指定注入时使用的构造函数。ObjectContext有多个构造函数,而且ObjectContext的构造函数代码是Visual Studio 代码生成的,最好的选择是使用配置文件或者使用配置API指定注入时使用的构造函数。下面是使用配置API:namespace RequestLifeTimeManagerTest
{public class EFContainerExtension : UnityContainerExtension   {protected override void Initialize(){this.Container.RegisterType<AdventureWorksLTEntities, AdventureWorksLTEntities>(new RequestControlledLifetimeManager(typeof(AdventureWorksLTEntities))).Configure<InjectedMembers>().ConfigureInjectionFor<AdventureWorksLTEntities>(new InjectionConstructor());}}
}我们定义了一个Unity扩展,在扩展类EFContainerExtension 我们选择了第一个构造函数以及ObjectContext使用RequestControlledLifetimeManager实现ObjectContext的生命周期管理。
2、实现RequestControlledLifetimeManager,完成对整个Request内都是一个ObjectContext的对象的生命周期管理:using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
namespace RequestLifeTimeManagerTest
{public class RequestControlledLifetimeManager : LifetimeManager{private Type objectType;/// <summary>   ///    /// </summary>   /// <param name="t"></param>   public RequestControlledLifetimeManager(Type t){this.objectType = t;}private IDictionary<Type, object> GetObjectTable(){IDictionary<Type, object> objects = HttpContext.Current.Items[RequestLifeTimeManagerTest.UnityHttpModule.UNITYOBJECTS]as IDictionary<Type, object>;if (objects == null){lock (this){if (HttpContext.Current.Items[RequestLifeTimeManagerTest.UnityHttpModule.UNITYOBJECTS] == null){objects = new Dictionary<Type, object>();HttpContext.Current.Items[RequestLifeTimeManagerTest.UnityHttpModule.UNITYOBJECTS] = objects;}else{return HttpContext.Current.Items[RequestLifeTimeManagerTest.UnityHttpModule.UNITYOBJECTS]as IDictionary<Type, object>;}}}return objects;}public override object GetValue(){IDictionary<Type, object> objects = this.GetObjectTable();object obj = null;if (objects.TryGetValue(this.objectType, out obj)){return obj;}return null;}public override void RemoveValue(){IDictionary<Type, object> objects = this.GetObjectTable();object obj = null;if (objects.TryGetValue(this.objectType, out obj)){((IDisposable)obj).Dispose();objects.Remove(this.objectType);}}public override void SetValue(object newValue){IDictionary<Type, object> objects = this.GetObjectTable();objects.Add(this.objectType, newValue);}}
}写一个HttpMoudle,在Request结束的时候回收资源。using System;
using System.Web;
using System.Collections.Generic;namespace RequestLifeTimeManagerTest
{public class UnityHttpModule : IHttpModule{internal const string UNITYOBJECTS = "UNITYOBJECTS";#region IHttpModule Memberspublic void Dispose(){//clean-up code here.}public void Init(HttpApplication context){context.EndRequest += new EventHandler(context_EndRequest);}#endregionprivate void context_EndRequest(object sender, EventArgs e){IDictionary<Type, object> objects = HttpContext.Current.Items[UNITYOBJECTS]as IDictionary<Type, object>;if (objects != null){foreach (Type key in objects.Keys){if (objects[key] is IDisposable){((IDisposable)objects[key]).Dispose();}}HttpContext.Current.Items.Remove(UNITYOBJECTS);}}}
}3、web.config中的配置文件内容如下,注意看红色部分:<?xml version="1.0"?>
<configuration><configSections><sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /><sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" /><section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /><section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /><section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /></sectionGroup></sectionGroup></sectionGroup><section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /></configSections><unity><typeAliases><typeAlias alias="string" type="System.String, mscorlib" /><typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /><typeAlias alias="transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity" /></typeAliases><containers>   <container><types><type type="RequestLifeTimeManagerTest.Gateways.IProductGateway,RequestLifeTimeManagerTest" mapTo="RequestLifeTimeManagerTest.Gateways.ProductGateway, RequestLifeTimeManagerTest"></type></types><extensions><add type="RequestLifeTimeManagerTest.EFContainerExtension, RequestLifeTimeManagerTest" /></extensions></container></containers></unity><appSettings /><connectionStrings><add name="AdventureWorksLTEntities" connectionString="metadata=res://*/AdventureWorksModel.csdl|res://*/AdventureWorksModel.ssdl|res://*/AdventureWorksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=GEFF-PC;Initial Catalog=AdventureWorksLT;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /></connectionStrings><system.web><!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development.--><compilation debug="true"><assemblies><add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /><add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /><add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /><add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation><!--The <authentication> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --><authentication mode="Windows" /><!--The <customErrors> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace.<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"><error statusCode="403" redirect="NoAccess.htm" /><error statusCode="404" redirect="FileNotFound.htm" /></customErrors>--><pages><controls><add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /></controls></pages><httpHandlers><!--<remove verb="*" path="*.aspx"/><add verb="*" path="*.aspx" type="RequestLifeTimeManagerTest.UnityHttpHandlerFactory, RequestLifeTimeManagerTest"/>--><remove verb="*" path="*.asmx" /><add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false" /></httpHandlers><httpModules><add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add name="UnityModule" type="RequestLifeTimeManagerTest.UnityHttpModule,RequestLifeTimeManagerTest"/>            </httpModules></system.web><system.codedom><compilers><compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><providerOption name="CompilerVersion" value="v3.5" /><providerOption name="WarnAsError" value="false" /></compiler></compilers></system.codedom><!-- The system.webServer section is required for running ASP.NET AJAX under InternetInformation Services 7.0.  It is not necessary for previous version of IIS.--><system.webServer><validation validateIntegratedModeConfiguration="false" /><modules><remove name="ScriptModule" /><add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /></modules><handlers><remove name="WebServiceHandlerFactory-Integrated" /><remove name="ScriptHandlerFactory" /><remove name="ScriptHandlerFactoryAppServices" /><remove name="ScriptResource" /><add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /></handlers></system.webServer><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" /></dependentAssembly></assemblyBinding></runtime>
</configuration>

本文来自云栖社区合作伙伴“doNET跨平台”,了解相关信息可以关注“opendotnet”微信公众号

自定义Unity对象生命周期管理集成ADO.NET Entity Framework相关推荐

  1. 容器,对象生命周期管理的基石

    2019独角兽企业重金招聘Python工程师标准>>> 郑重申明:包括本文在内的很多技术文章,大多出自山外高人,而非Fans. Fans暂时没有能力写作优秀的技术文章,Fans只是转 ...

  2. SSH学习-Hibernate对象生命周期管理

    Hibernate对象就是java中的实体对象,管理就是在实体对象的生命周期内被Hibernate的操作,Hibernate对象的生命周期其实就是实体对象的生命周期(从创建到最后被GC回收),期间对实 ...

  3. MinIO对象生命周期管理解析

    目录 前言 对象过期 远程存储层(Tiers)常用分层场景 跨存储介质 跨云类型 公有云 文件迁移实例 Tiers配置 生成周期管理配置 原始桶的tiertest前缀的文件目录 远程存储层目录结构 原 ...

  4. Linux多线程服务端编程笔记,陈硕Linux多线程服务端编程读书笔记 —— 第一章 线程安全的对象生命周期管理...

    muduo书第一章的思维导图(新窗口打开可以看大图) 线程安全的对象析构和回调(使用shared_ptr和weak_ptr) 注释是英文的(工地英语-) StockFactory.h // in mu ...

  5. ASP.NET Core Web API下事件驱动型架构的实现(二):事件处理器中对象生命周期的管理

    在ASP.NET Core Web API下事件驱动型架构的实现(一):一个简单的实现中,我介绍了事件驱动型架构的一种简单的实现,并演示了一个完整的事件派发.订阅和处理的流程.这种实现太简单了,百十行 ...

  6. Spring IoC容器与Bean管理18:Bean对象的作用域及生命周期三:对象生命周期;

    说明: (1)本篇博客主要根据案例阐述对象的声明周期: (2)其中,比较重要的是注意下这个对应关系: (3)还有就是调用[registerShutdownHook()]销毁IoC容器: 目录 一:be ...

  7. 技术指南 | 如何集成Perforce版本控制系统Helix Core (P4V) 与软件生命周期管理工具Helix ALM

    Helix Core是Perforce公司旗下一款集源代码管理和内容协作为一体的版本配置与管理工具,可以帮助您管理随时间推移而产生的数字资产(代码,文件等)变更,处理每天数以千万计的传输,上千TB的数 ...

  8. 项目全生命周期管理、资产成果沉淀展示、算力资源灵活调度丨ModelWhale 云端协同创新平台全面赋能数据驱动科研工作

    新基建的浪潮如火如荼,国家顶层政策的引导不仅支持着由数据驱动各垂直领域中的新兴商业市场,也为相关科研市场的发展提供了众多机遇. 但持续的发展也带来了新的问题,传统基础设施已逐渐不能响应新兴数据驱动研究 ...

  9. 组件生命周期管理和通信方案

    随着移动互联网的快速发展,项目的迭代速度越来越快,需求改变越来越频繁,传统开发方式的工程所面临的一些,如代码耦合严重.维护效率低.开发不够敏捷等问题就凸现了出来.于是越来越多的公司开始推行" ...

最新文章

  1. Android studio 另一个程序正在使用此文件,进程无法访问
  2. linux 改用户组密码,Linux用户和组的操作(八) 修改用户密码 passwd
  3. 关于Qt的事件循环以及QEventLoop的简单使用
  4. android ffmpeg编译so,Android FFmpeg学习(一),将FFmpeg编译成so文件
  5. access 报表中序号自动_Access中自动编号的字段ID如何让它重新从初始值1开始编号...
  6. EXECUTE IMMEDIATE oracle介绍
  7. 网管工具 dstat
  8. PCIE 协议分析工具
  9. Pug/jade快速上手教程
  10. 一起来全面解析5G网络领域最关键的十大技术
  11. 机器学习——逻辑回归算法代码实现
  12. 魔兽三界血歌鸿蒙武器怎么合成,《伏魔战记》关于武器材料出处以及合成以及对一些武器的使用心的...
  13. 互联网日报 | 4月1日 星期四 | 华为2020年收入8914亿元;滴滴拿下消费金融牌照;HM已在中国关闭约20家门店...
  14. 鸿蒙二部曲之一,网文封神之作,“鸿蒙二部曲”和“斗罗四部曲”你选择站哪边?...
  15. STM32的引脚的配置
  16. 全球首个3万亿美元公司!苹果实现全球最高市值里程碑
  17. 网络协议与服务的区别/关系
  18. 动物实验可用计算机模拟,《动物实验类试题》.doc
  19. win11 右下角图标(网络,音量,电量)点击无反应解决方法
  20. Java小白从入门到入土 Day03

热门文章

  1. 设计模式:建造者模式
  2. 设计模式:设计模式七大原则之迪米特法则
  3. C语言文件操作解析(二)
  4. IDEA快速入门(Mac版)
  5. Vue 教程第十七 篇—— Vuex 之 module
  6. Appcan页面跳转
  7. singleton模式四种线程安全的实现
  8. apply() filter()
  9. HP ML110/120 G7配置阵列卡安装server 2003
  10. flex与java实现增删改查