有没有办法反编译由NHibernate 4.0生成的动态代理类?

时间:2015-10-19 01:59:51

标签: c# nhibernate proxy

This question was already asked here on SO但答案是指NHibernate 3.2.0。

那么,有没有办法对NHibernate 4.0生成的动态代理类进行反编译?

1 个答案:

答案 0 :(得分:0)

使用自定义Proxyfactory应该可以解决问题。示例配置使用FluentNHibernate

var config = Fluently.Configure()
    .ProxyFactoryFactory<MyProxyFactoryFactory>()

使用类

class MyProxyFactoryFactory : DefaultProxyFactoryFactory, IProxyFactoryFactory
{
    IProxyFactory IProxyFactoryFactory.BuildProxyFactory()
    {
        return new MyProxyFactory();
    }
}

class MyProxyFactory : AbstractProxyFactory, IProxyAssemblyBuilder
{
    const string PathToSave = "D:/";

    private readonly ProxyFactory factory;

    public MyProxyFactory()
    {
        factory = new ProxyFactory(this);
    }

    public override INHibernateProxy GetProxy(object id, ISessionImplementor session)
    {
        try
        {
            var initializer = new DefaultLazyInitializer(EntityName, PersistentClass, id, GetIdentifierMethod, SetIdentifierMethod, ComponentIdType, session);

            object proxyInstance = IsClassProxy
                                    ? factory.CreateProxy(PersistentClass, initializer, Interfaces)
                                    : factory.CreateProxy(Interfaces[0], initializer, Interfaces);

            return (INHibernateProxy)proxyInstance;
        }
        catch (Exception ex)
        {
            throw new HibernateException("Creating a proxy instance failed", ex);
        }
    }

    public override object GetFieldInterceptionProxy(object instanceToWrap)
    {
        var interceptor = new DefaultDynamicLazyFieldInterceptor();
        return factory.CreateProxy(PersistentClass, interceptor, new[] { typeof(IFieldInterceptorAccessor) });
    }

    public AssemblyBuilder DefineDynamicAssembly(AppDomain appDomain, AssemblyName name)
    {
        return appDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, PathToSave);
    }

    public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName)
    {
        return assemblyBuilder.DefineDynamicModule(moduleName, moduleName + ".mod", true);
    }

    public void Save(AssemblyBuilder assemblyBuilder)
    {
        assemblyBuilder.Save("generatedAssembly.dll");
    }
}