Wednesday, December 29, 2010

Fluent NHibernate AddFromNamespaceOf. The overlooked method of Fluent NHibernate

Unless I'm missing something, writing AddFromNamespaceOf method is a simple undertaking

public static class Helper
{

    public static FluentMappingsContainer AddFromNamespaceOf<T>(
           this FluentMappingsContainer fmc)
    {
        Type t = typeof(T);
        string ns = t.Namespace;
        
    
        var y = from x in t.Assembly.GetTypes()
                where 
                    x.FullName == ns + "." + x.Name
                    && x.BaseType.IsGenericType                        
                    && x.BaseType.GetGenericTypeDefinition().IsDerivedFrom(typeof(ClassMap<>))
                select x;
                
        foreach(Type z in y)
            fmc.Add(z);                 
    
        
        return fmc;
    }
    
    private static bool IsDerivedFrom(this Type givenType, Type genericType)
    {
        if (givenType == genericType)
            return true;
        
        if (givenType.BaseType.IsGenericType)
            return givenType.BaseType
                .GetGenericTypeDefinition().IsDerivedFrom(genericType);
        
        return false;
    }
}  

Useful when doing unit tests or other kind of testing and don't want to be bothered with creating separate projects/assembly for group of entities. Example: http://code.google.com/p/fluent-nhibernate-lowercase-system/source/browse/#svn

No comments:

Post a Comment