Fluentnhibernate AttributePropertyConvention

By Deathraven on Tuesday 4 June 2013 11:04
Category: Software Development, Views: 2.833

Fluentnhibernate's AttributePropertyConvention is great. It allows you to use the conventions feature, but still allows you to customize where needed.

Unfortunatly they dont work on reference types. You can fix that by creating your own AttributeReferenceConvention type like so.


C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
public abstract class AttributeReferenceConvention<T> : IReferenceConvention, IReferenceConventionAcceptance where T : Attribute {
         public void Accept(IAcceptanceCriteria<IManyToOneInspector> criteria) {
             criteria.Expect(property => Attribute.GetCustomAttribute(property.Property.MemberInfo, typeof(T)) as T != null);
        }
        
        public void Apply(IManyToOneInstance instance) {
             var attribute = Attribute.GetCustomAttribute(instance.Property.MemberInfo, typeof(T)) as T;

            Apply(attribute, instance);
        }

        protected abstract void Apply(T attribute, IManyToOneInstance instance);
    }



In my case I wanted to override the lazy loading settings for a specific reference. Now I can do that like this:


C#:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class EagerLoadingConvention : AttributeReferenceConvention<EagerLoadingAttribute>
    {
        protected override void Apply(EagerLoadingAttribute attribute, IManyToOneInstance instance) {
           instance.Not.LazyLoad();
            instance.Fetch.Join();
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class EagerLoadingAttribute : Attribute
    {
        public EagerLoadingAttribute()
        {

        }
    }

Volgende: Cross module communication with Autofac Part 1 04-'11 Cross module communication with Autofac Part 1

Comments

Comments are closed