Search code examples
c#nhibernategenericsninjectninject-2

How to make a generic nhibernate repository that works with ninject?


I am trying to make my first generic repository. I am starting with the real simple ones but I am unsure how to hook it all up to ninject and use it through constructor injection.

   public class NhibernateRepo<T> : INhibernateRepo<T>
    {
        private readonly ISession session;

        public NhibernateRepo(ISession session)
        {
            this.session = session;
        }

        public void Commit()
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                transaction.Commit();
            }
        }

        public void Delete(T entity)
        {
            session.Delete(entity);
        }

        public void Update(T entity)
        {
            session.Update(entity);
        }

        public T Get(object id)
        {
            return session.Get<T>(id);
        }

        public T Load(object id)
        {
            return session.Load<T>(id);
        }

        public void ReadOnly(object entity, bool readOnly = true)
        {
            session.SetReadOnly(entity, readOnly);
        }

        public void Evict(object entity)
        {
            session.Evict(entity);
        }

        public object Merge(object entity)
        {
            return session.Merge(entity);
        }
    } 

public interface INhibernateRepo<T>
    {
        void Commit();
        void Delete(T entity);
        void Update(T entity);
        T Get(object id);
        T Load(object id);
        void ReadOnly(object entity, bool readOnly = true);
        void Evict(object entity);
        object Merge(object entity);
    }
}

Now I want to use this in my service layer. So I was trying to do

public MyServiceLayer(INhibernateRepo nhibernateRepo)

But it does not like that so I tried

public  MyServiceLayer(INhibernateRepo<T> nhibernateRepo)

but it could not find T.

So how do I do this? I am guessing doing the binding will be a challenge too so I am unsure how to do that.


Solution

  • Try moving <T> from interface-level to method-level. Like so:

    public void Delete<T>(T instance) ...