首页 > 编程 > Python > 正文

扩展 IronPython for ASP.NET:编写自定义属性注入器

2019-11-18 16:48:18
字体:
来源:转载
供稿:网友

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'


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表