A Curious Mind
#tastic

NHibernate, Generics, and Dependency Injection : A sweet recipie

Thursday, July 06, 2006 5:17 PM

Recently Castle has added support for Generics in their MicroKernel. This has lead to some wicked awesome code, thanks to some great ideas from Ayende.

Ok, so I am going to try and explain a simple example using NHibernate

public interface Repository<T>
{
    T Find(Guid id);
}

and a NHibernate Implementation (here is the Find(Guid id) method)

public class NHibernateRepository<T> : Repository<T>
{
    //ctor to set up NHibernate stuff

    public T Find(Guid id)
    {
        ISession sess = GetSession();
        return sess.Get(typeof(T), id) as T;
    }
}

Now we have a NHibernateRepository that is strongly typed for each of my entities registered with NHibernate. Instead of having to write a strongly-typed repository for each entity I now just register this in the kernel and I can pull out any instance with any Type I want.

Next: Why this is cool


Feedback

# re: NHibernate, Generics, and Dependency Injection : A sweet recipie

I wanted to do a similar thing except I'd make my DAO generic (IDao<T>) since I only use aggregate roots for my repositories 8/15/2006 6:25 PM | Mike

# re: NHibernate, Generics, and Dependency Injection : A sweet recipie

Doh! HTML ate my &lt;T&gt;. Thanks Mike. I love it and it is stupid simple. 8/15/2006 6:32 PM | dru

Post a comment





 

Please add 5 and 4 and type the answer here: