Skip to content

Instantly share code, notes, and snippets.

@oillio
Created August 21, 2010 03:03
Show Gist options
  • Save oillio/541691 to your computer and use it in GitHub Desktop.
Save oillio/541691 to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using Castle.ActiveRecord;
using NHibernate;
using NHibernate.Engine;
using NHibernate.Type;
namespace ActiveRecordUtil.ByteCode {
class LazyInitializer : NHibernate.ByteCode.Castle.LazyInitializer {
public LazyInitializer(string entityName, Type persistentClass, object id,
MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod,
IAbstractComponentType componentIdType, ISessionImplementor session)
:base(entityName, persistentClass, id, getIdentifierMethod, setIdentifierMethod, componentIdType, session) {
}
/// <summary>
/// Perform an ImmediateLoad of the actual object for the Proxy.
/// </summary>
public override void Initialize() {
ISession newSession = null;
try {
if (IsUninitialized) {
if (Session == null ||
!Session.IsOpen ||
!Session.IsConnected) {
newSession = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(PersistentClass);
Session = newSession.GetSessionImplementation();
}
}
base.Initialize();
}
finally {
if (newSession != null) ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(newSession);
}
}
}
}
using System;
using Castle.DynamicProxy;
using NHibernate;
using NHibernate.Engine;
using NHibernate.Proxy;
namespace ActiveRecordUtil.ByteCode {
class ProxyFactory : NHibernate.ByteCode.Castle.ProxyFactory {
private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();
public override INHibernateProxy GetProxy(object id, ISessionImplementor session) {
try {
var initializer = new LazyInitializer(EntityName, PersistentClass, id, GetIdentifierMethod,
SetIdentifierMethod, ComponentIdType, session);
object generatedProxy = IsClassProxy
? ProxyGenerator.CreateClassProxy(PersistentClass, Interfaces, initializer)
: ProxyGenerator.CreateInterfaceProxyWithoutTarget(Interfaces[0], Interfaces,
initializer);
initializer._constructed = true;
return (INHibernateProxy)generatedProxy;
} catch (Exception e) {
log.Error("Creating a proxy instance failed", e);
throw new HibernateException("Creating a proxy instance failed", e);
}
}
}
}
using NHibernate.Bytecode;
using NHibernate.Proxy;
namespace ActiveRecordUtil.ByteCode {
public class ProxyFactoryFactory : IProxyFactoryFactory {
public IProxyFactory BuildProxyFactory() {
return new ProxyFactory();
}
public IProxyValidator ProxyValidator {
get { return new DynProxyTypeValidator(); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment