用在Unity中,如何获取对象的实例及如何销毁对象都是由LifetimeManager完成的,其定义如下
public abstract class LifetimeManager : ILifetimePolicy,
IBuilderPolicy
{
    protected LifetimeManager();

说明一下,主要是通过jquery的getjson方法去取得wcf返回的数据,传参方法:

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

<buildProviders>
<remove extension=”.svc”/>
<add extension=”.svc”
type=”System.ServiceModel.Activation.ServiceBuildProvider,System.ServiceModel,
Version=3.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089″/>
</buildProviders>
</compilation>

        public override void SetValue(object newValue)
        {
            IDictionary<Type, object> objects =
this.GetObjectTable();
            objects.Add(this.objectType, newValue);
        }
    }
}

复制代码 代码如下:

我们定义了一个Unity扩展,在扩展类EFContainerExtension
我们选择了第一个构造函数以及ObjectContext使用RequestControlledLifetimeManager实现ObjectContext的生命周期管理。

<services>
<service name=”imgService”>
<endpoint address=””
behaviorConfiguration=”imgServiceAspNetAjaxBehavior”
binding=”webHttpBinding” contract=”imgService” />
</service>
</services>
</system.serviceModel>
</configuration>

        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 abstract object GetValue();
    public abstract void RemoveValue();
    public abstract void SetValue(object newValue);
}

<httpErrors errorMode=”Detailed” />
<asp scriptErrorSentToBrowser=”true”/>

        public void Init(HttpApplication context)
        {
            context.EndRequest += new EventHandler(context_EndRequest);

[ServiceContract(Namespace = “”)]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class imgService
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为
WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType =
“text/xml”;
[OperationContract]
[WebGet(RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
//[WebInvoke(Method = “GET”, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,BodyStyle =
WebMessageBodyStyle.WrappedRequest)]
public DataTable GetDataTable(string pz)
{
// 在此处添加操作实现
DataSet ds = WebBase.GetDS(WebBase.meinvRepository, string.Empty, ”
body_id desc”,pz);
if (ds.Tables.Count > 0)
return ds.Tables[0];
return null;
}

// Original file name:
// Generation date: 2008/8/24 10:05:33
namespace RequestLifeTimeManagerTest
{
    using Microsoft.Practices.Unity;

好的,成功!上传到gd空间试试 🙂

构造函数注入包含了二种情况,一种是类仅有一个构造函数时,Unity
可以进行自动注入;另一种情况是,类包含多个构造函数时,必须使用 Attribute
或者配置文件指定注入时使用的构造函数。

$.getJSON(url, { pz: “6” }, function (msg)
{alert(msg.d)});这里是返回6条数据还有wcf的svc上加上属性:
Factory=System.ServiceModel.Activation.WebScriptServiceHostFactory还有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="Data Source=GEFF-PC;Initial
Catalog=AdventureWorksLT;Integrated
Security=True;MultipleActiveResultSets=True"”
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.

复制代码 代码如下:

       <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 Internet
        Information 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>

http://www.bkjia.com/Javascript/327308.htmlwww.bkjia.comtruehttp://www.bkjia.com/Javascript/327308.htmlTechArticle首选创能wcf,代码很简单,如下: 复制代码
代码如下: using System; using System.Data; using System.ServiceModel;
using System.ServiceModel.Activation; using Syst…

        public void Dispose()
        {
            //clean-up code here.
        }

复制代码 代码如下:

在Unity中,从Unity 取得的实例为
Transient。如果你希望使用多线程方式,就需要在组成时使用lifecycle参数,这时候取出的组件就不再是同一个了。在Unity
IOC中,它支持我们对于组件的实例进行控制,也就是说我们可以透明的管理一个组件拥有多少个实例。Unity
IOC容器提供了如下几种生命处理方式:
#
Singleton:一个组件只有一个实例被创建,所有请求的客户使用程序得到的都是同一个实例。
#
Transient:这种处理方式与我们平时使用new的效果是一样的,对于每次的请求得到的都是一个新的实例。
# Custom:自定义的生命处理方式。

$.getJSON(url, { pz: “6” }, function (msg) {
$(msg.d).find(“Table”).each(function (i) {
var rq =
$(this).children(“Body_AddTime”).text().split(‘T’)[0].replace(“-“,
“”).replace(“-“, “”);
rq = rq.substring(0, rq.length – 2);
var html = ‘<li><a href=”http://meinv.vs2010.com/topic/‘ +
$(this).children(“Body_MuLuID”).text() + ‘/’ + rq + ‘/show-id’ +
$(this).children(“Body_ID”).text() + ‘.html”
target=”_blank”><img src=”http://meinv.vs2010.com/‘ +
$(this).children(“Body_Tu”).text() + ‘” />’ +
$(this).children(“Body_Name”).text() + ‘</a></li>’;
$(“.main ul”).append(html);
});
});

        }

<%@ Page Language=”C#” EnableViewState=”false”
AutoEventWireup=”true” CodeFile=”Default.aspx.cs”
Inherits=”jquerywcf_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns=”http://www.w3.org/1999/xhtml"&gt;
<head id=”Head1″ runat=”server”>
<title></title>
<script src=”../Scripts/jquery-1.4.1-vsdoc.js”
type=”text/javascript”></script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div class=”main”>
<ul><li><a></a></li></ul>
</div>
<div>
<script type=”text/javascript”>
function sendAJAX(data) {
var url = “<%=_url %>imgService.svc/GetDataTable”;

2、实现RequestControlledLifetimeManager,完成对整个Request内都是一个ObjectContext的对象的生命周期管理:

<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>

ObjectContext有多个构造函数,而且ObjectContext的构造函数代码是Visual
Studio
代码生成的,最好的选择是使用配置文件或者使用配置API指定注入时使用的构造函数。下面是使用配置API:

// 在此处添加更多操作并使用 [OperationContract] 标记它们
}

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

<add assembly=”System.ServiceModel, Version=3.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089″/>
<add assembly=”System.ServiceModel.Web, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35″/>
</assemblies>

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

<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name=”imgServiceAspNetAjaxBehavior”>
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” >
<baseAddressPrefixFilters>
<!–<add prefix=”http://demo.vs2010.com"/&gt;–&gt;
</baseAddressPrefixFilters>
</serviceHostingEnvironment>

namespace RequestLifeTimeManagerTest
{
    public class UnityHttpModule : IHttpModule
    {
        internal const string UNITYOBJECTS = “UNITYOBJECTS”;
        #region IHttpModule Members

<httpHandlers>
<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=”ServiceModel”
type=”System.ServiceModel.Activation.HttpModule, System.ServiceModel,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089″/>
</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>
<compiler language=”vb;vbs;visualbasic;vbscript” extension=”.vb”
warningLevel=”4″
type=”Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089″>
<providerOption name=”CompilerVersion” value=”v3.5″/>
<providerOption name=”OptionInfer” value=”true”/>
<providerOption name=”WarnAsError” value=”false”/>
</compiler>
</compilers>
</system.codedom>
<!–
system.webServer 节是在 Internet Information Services 7.0 下运行 ASP.NET
AJAX
所必需的。对早期版本的 IIS 来说则不需要此节。
–>
<system.webServer>
<validation validateIntegratedModeConfiguration=”false”/>
<urlCompression doStaticCompression=”true”
doDynamicCompression=”true”/>

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

using System;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web.Script.Services;

        public override object GetValue()
        {
            IDictionary<Type, object> objects =
this.GetObjectTable();
            object obj = null;
            if (objects.TryGetValue(this.objectType, out obj))
            {
                return obj;
            }
            return null;
        }

<add verb=”*” path=”*.ashx” name=”AjaxPro”
type=”AjaxPro.AjaxHandlerFactory,AjaxPro.2″/>
<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 appliesTo=”v2.0.50727″
xmlns=”urn:schemas-microsoft-com:asm.v1″>
<dependentAssembly>
<assemblyIdentity name=”MySql.Data”
publicKeyToken=”C5687FC88969C44D”/>
<!–<bindingRedirect oldVersion=”5.0.7.0″
newVersion=”6.3.2.0″/>–>
<bindingRedirect oldVersion=”5.0.7.0″ newVersion=”6.2.3.0″/>
</dependentAssembly>
<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>

}

<!–
通过 <authentication> 节可以配置
安全身份验证模式,ASP.NET
使用该模式来识别来访用户身份。
–>
<authentication mode=”Windows” />
<!–
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节
可以配置相应的处理步骤。具体而言,
开发人员通过该节可配置要显示的 html 错误页,
以代替错误堆栈跟踪。

        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);
            }
        }

<?xml version=”1.0″?>
2 <configuration>
3
4 <configSections>
5 <!–ajax–>
6 <sectionGroup name=”ajaxNet”>
7 <section name=”ajaxSettings”
type=”AjaxPro.AjaxSettingsSectionHandler,AjaxPro.2″
requirePermission=”false” restartOnExternalChanges=”true”/>
8 </sectionGroup>
9 <!–ajax–>
<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>
</configSections>
<appSettings/>
<connectionStrings>
<add name=”meinvvs2010ConnectionString”
connectionString=”server=127.0.0.1;user id=test; password=test;
database=test;pooling=false”
providerName=”MySql.Data.MySqlClient”/>
</connectionStrings>
<!–ajax–>
<ajaxNet>
<ajaxSettings>
<urlNamespaceMappings useAssemblyQualifiedName=”false”
allowListOnly=”false”/>
<jsonConverters includeTypeProperty=”true”/>
<debug enabled=”false”/>
<token enabled=”false” sitePassword=”password”/>
</ajaxSettings>
</ajaxNet>
<location path=”ajaxpro” allowOverride=”true”
inheritInChildApplications=”false”>
<system.web>
<globalization requestEncoding=”utf-8″ responseEncoding=”utf-8″
fileEncoding=”utf-8″/>
<!–for iis7
<system.webServer>
<handlers>
<add verb=”*” path=”*.ashx” name=”AjaxPro”
type=”AjaxPro.AjaxHandlerFactory,AjaxPro.2″/>
</handlers>
</system.webServer>–>
<!–for iis6–>
<httpHandlers>
<add verb=”*” path=”*.ashx”
type=”AjaxPro.AjaxHandlerFactory,AjaxPro.2″/>
</httpHandlers>
</system.web>
</location>
<!–ajax–>
<system.web>
<customErrors mode=”Off”/>
<compilation debug=”true”>
<assemblies>
<add assembly=”System.Core, 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.Data.DataSetExtensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=B77A5C561934E089″/>
<add assembly=”System.Xml.Linq, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089″/>

        private 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);
            }
        }

<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” />
<remove name=”svc” />
<add name=”svc” path=”*.svc” verb=”*”
type=”System.ServiceModel.Activation.HttpHandler, System.ServiceModel,
Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″
preCondition=”integratedMode” />

        #endregion

页面调用方法也很简单:

……

首选创能wcf,代码很简单,如下:

using System;
using System.Web;
using System.Collections.Generic;

$(function () {
sendAJAX();
});
</script>
<div id=”msg”>
</div>
</div>
</form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;

说明一下,wcf就一个GetDataTable方法,有一个参数pz表示返回数据的行数,返回的table以json数据给jquery使用

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());
        }
    }
}

    }
}

namespace RequestLifeTimeManagerTest
{
    public class RequestControlledLifetimeManager : LifetimeManager
    {
        private Type objectType;

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

 

        <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″ />

写一个HttpMoudle,在Request结束的时候回收资源。

    /// <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();

        /// <summary>  
        ///   
        /// </summary>  
        /// <param name=”t”></param>  
        public RequestControlledLifetimeManager(Type t)
        {
            this.objectType = t;
        }

 

3、web.config中的配置文件内容如下,注意看红色部分:

admin

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注