首页 | IT新闻 | 硬件 | 操作系统 | 开发 | 网络编程 | 数据库 | 热门框架 | 网络安全 | 组网 | 建站指南 | 网页制作 | 特效 | 实用技巧 | 服务器 | 办公 | QQ | 探索 | 社区

  • 技术部落
  • 部落首页 > 程序开发 > .NET专栏 > 正文
  • 扩展IronPython for ASP.NET:编写自定义属性注入器
      2007-3-6  来源:网络资源  编辑:Jsbulo  热度:

    IronPython for ASP.NET 的属性注入器机制可以使得一些代码的语法变得简单(详细了解参考我的这一篇),但是默认的支持似乎现在还很不完备。
    我反编译了 Microsoft.Web.IronPython.dll,在其中增加了对 RepeaterItem 和 Session (HttpSessionState) 的属性注入支持。

    对 RepeaterItem 的支持很简单,因为本身已经有了 ControlAttributesInjector. 所以只要在 DynamicLanguageHttpModule.cs 的静态构造器中加一行代码即可:

    // repeater item
    Ops.RegisterAttributesInjectorForType(typeof(RepeaterItem), new ControlAttributesInjector(), false);
    而 Session 则不那么幸运,这个类实现了 ICollection,但是确没有实现 IDictionary 接口。所以就无法利用 DictionaryAttributesInjector. 没办法,我自己给加了个 SessionAttributesInjector 类。代码如下:

    using IronPython.Runtime;
    using System;
    using System.Collections;
    using System.Runtime.InteropServices;
    using System.Web.SessionState;
    using System.Diagnostics;

    namespace Microsoft.Web.IronPython.AttributesInjectors {
        // added by Neil Chen.
        internal class SessionAttributesInjector: IAttributesInjector {
            List IAttributesInjector.GetAttrNames(object obj) {           
                HttpSessionState session = obj as HttpSessionState;
                List list = new List();
                foreach (string key in session.Keys) {
                    list.Add(key);
                }
                return list;
            }

            bool IAttributesInjector.TryGetAttr(object obj, SymbolId nameSymbol, out object value) {
                HttpSessionState session = obj as HttpSessionState;
                value = session[nameSymbol.GetString()];
                return true;
            }
        }
    }

    附上我修改过的 Microsoft.Web.IronPython.dll

    需要说明的是,属性注入器只对 get 操作有用,比如
    name = Session.Name 是可以的,

    但是设置则不行:
    Session.Name = ’some name’ 会报错。

    还是需要用这个语法:
    Session["Name"] = ’some name’