2

有谁知道是否可以控制通过 Castle DynamicProxy 生成的类型的名称?我希望利用持久化 Castle 生成的程序集的能力,为我的项目添加一些具有某些特定功能的附加类,但我希望能够控制这些生成的代理类型的名称。任何帮助将不胜感激。

我实际上计划保留这些类的实例以及作为 NHibernate 代理源的原始类的实例。因此,我需要这些名称在多代程序集中保持一致。

4

2 回答 2

3

我做了一些有趣的挖掘。使用 INamingScope 指定代理名称似乎是可能的,但将 INamingScope 嵌入其中远非简单。您需要创建自己的 ProxyFactoryFactory,这将创建一个与 NHibernate.ByteCode.Castle.ProxyFactory 相同的 ProxyFactory,除了它将初始化 ProxyGenerator:

public class CustomProxyFactory : AbstractProxyFactory {
    private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator(new CustomProxyBuilder());
    // remainder of code is identical
}

public class CustomProxyBuilder : DefaultProxyBuilder {
    public CustomProxyBuilder() : base(new CustomModuleScope()) {}
}

public class CustomModuleScope : ModuleScope {
    public CustomModuleScope() : base(false, false, new CustomNamingScope(), DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME, DEFAULT_ASSEMBLY_NAME, DEFAULT_FILE_NAME) {}
}

public class CustomNamingScope : INamingScope {
    public CustomNamingScope() {}

    private CustomNamingScope(INamingScope parent) {
        ParentScope = parent;
    }

    public string GetUniqueName(string suggestedName) {
        // your naming logic goes here
    }

    public INamingScope SafeSubScope() {
        return new CustomModuleScope(this);
    }

    public INamingScope ParentScope { get; private set; }
}

老实说,我没有尝试过运行或编译任何这些。只是挖掘 NHibernate 和 Castle.Core 源代码。希望它能给你一些想法......

于 2010-11-18T20:09:39.837 回答
0

看看 NHContrib 中的 ProxyGenerators 项目。它允许您预先生成 NHibernate 的延迟加载代理。

http://nhforge.org/wikis/proxygenerators10/default.aspx

无论您是否使用 ProxyGenerators,您都可以通过 Proxy Factory Factory 将您的自定义代理集成到 NHibernate 中。在 hibernate.cfg.xml 中:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="proxyfactory.factory_class">YOUR_PROXY_FACTORY_FACTORY</property>
  </session-factory>
</hibernate-configuration>
于 2010-11-17T18:05:06.560 回答