NHiberante Could not initialize proxy - no Session

97 Views Asked by At

this is my piece of code, which I use inside the class protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {

to check if the properties I have in the object are serializable or not

if (property.ShouldSerialize == null) {
            property.ShouldSerialize = instance => {
                try {
                    PropertyInfo prop = (PropertyInfo)member;
                    if (prop.CanRead) {
                        var value = prop.GetValue(instance, null);
                        
                        if (value != null
                            && value.GetType().IsSubclassOfRawGeneric(typeof(NHibernate.Collection.Generic.PersistentGenericBag<>))
                            && !((value as NHibernate.Collection.AbstractPersistentCollection).WasInitialized)) {
                            return false;
                        }
                        return true;
                    }
                }
                catch (Exception e) {
                    var m = e.Message;
                }
                return false;
            };
        }

prop.GetValue(instance, null); fails with the proxy error, can I intervene at this level without touching the data structure of the object?

I have tried setting ReferenceLoopHandling as ignore, but with little result.

1

There are 1 best solutions below

0
Paulo Henrique On

Based on your idea, I was able to solve my problem of proxies objects as follows:

public class NHibernateContractResolver : DefaultContractResolver {

    protected override JsonContract CreateContract(Type objectType) {
        if (typeof(INHibernateProxy).IsAssignableFrom(objectType)) {
            return base.CreateObjectContract(objectType);
            //return base.CreateContract(objectType.BaseType);
        }
        return base.CreateContract(objectType);
    }
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        property.ShouldSerialize = instance => {
            {
                try {
                    PropertyInfo prop = (PropertyInfo)member;
                    if (prop.CanRead) {
                        var value = prop.GetValue(instance, null);
                        if (value != null
                        && value.GetType().Name.Equals("PersistentGenericBag`1")) {
                            var item = ((IList)value)[0];
                        }
                        return true;
                    }
                    return false;
                } catch (Exception) {
                    return false;
                }
            };
        };
        return property;
    }