阿瑞空间

---------激情而不浮躁-------
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

上下文绑定对象之一(定义)

Posted on 2008-09-24 17:22  阿瑞  阅读(850)  评论(0编辑  收藏  举报

  上下文的概念,我们平时工作中可能接触的不多,其实在.net框架中,上下文是一个基础概念,以至于我们写的代码时刻都与它保持着接触,这篇文章我们就来探讨一下上下文与上下文绑定对象。

  在.net中,有这样一个类Context, 它位于System.Runtime.Remoting.Contexts命名空间中,先别在意这个命名空间为什么这么长,当一个托管的应用程序开始运行,我们知道首先会创建一个默认应用程序域(AppDomain), 而这个默认应用程序域又会创建一个Context类的实例,称之为默认上下文,我们可以通过Context.DefaultContext来得到这个默认上下文的信息,对每一个线程,我们同样可以通过Thread.CurrentContext得到这个线程运行所处的上下文。

 

MyContextPropery 
public class MyContextPropery : IContextProperty
{
#region IContextProperty Members

public string Name
{
get { return "MyContextPropery"; }
}

public bool IsNewContextOK(Context newCtx)
{
return true;
}

public void Freeze(Context newContext)
{
}

#endregion
}

 

上面是一定简单的上下文属性类型,我们只是实现了IContextProperty中定义的方法。

现在我们有了上下文MyContextObject和上下文属性MyContextPropery,下面我们要把上下文属性绑定到上下文对象中,该IContextAttribute出场了。

MyContextAttribute 
[AttributeUsage(AttributeTargets.Class)]
public class MyContextAttribute : Attribute, IContextAttribute
{
#region IContextAttribute Members

public void GetPropertiesForNewContext(IConstructionCallMessage msg)
{
IContextProperty myContextProperty
= new MyContextPropery();
msg.ContextProperties.Add(myContextProperty);
}

public bool IsContextOK(Context ctx, IConstructionCallMessage msg)
{
// Here we ensure the MyContextPropery exist in the context's properties.
if (ctx.GetProperty("MyContextPropery") == null)
{
return false;
}
return true;
}

#endregion
}

 

  现在,CLR在激活MyContextObject对象过程中就会保证该对象的上下文中一定存在MyContextPropery属性,我们通过PrintContextProperties来验证是否存在。