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



  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# 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

Comments have been closed on this topic.