Ninject getting a generic type in ToMethod
I have a repository like this:
public class Repository<T> : IRepository<T> where T : class
{
private readonly ISession session;
public Repository(ISession session)
{
this.session = session;
}
}
I use NHQS and I usually do this to get a ISession object:
SessionFactory.For<T>().OpenSession();
How do I setup Ninject to create a session automatically for the requested type and bind it? I tried this but I don't know what to put in the For<>():
kernel.Bind(typeof(IRepository<>开发者_高级运维))
.To(typeof(Repository<>))
.WithConstructorArgument("session", SessionFactory.For<>().OpenSession());
Looks like I need to get the generic type being used and pass it in the For<>()
How do I do that?
You should'nt use WithConstructorArgument
; create a binding for ISession instead.
kernel.Bind<ISession>.ToMethod(context => ....).InRequestScope();
You can get the IRepository<>
type from context.Request.ParentRequest.Service
. You can now extract the entity type using reflection. However, if you are using the same database for all entities then it is probably easier to return a general session for all repositories.
精彩评论