Ninject 在 ToMethod 中获取泛型类型
我有一个像这样的存储库:
public class Repository<T> : IRepository<T> where T : class
{
private readonly ISession session;
public Repository(ISession session)
{
this.session = session;
}
}
我使用 NHQS 并且我通常这样做来获取 ISession 对象:
SessionFactory.For<T>().OpenSession();
如何我设置 Ninject 自动为请求的类型创建会话并绑定它?我尝试了这个,但我不知道要在 For<>() 中放入什么:
kernel.Bind(typeof(IRepository<>))
.To(typeof(Repository<>))
.WithConstructorArgument("session", SessionFactory.For<>().OpenSession());
看起来我需要获取正在使用的泛型类型并将其传递到 For<>()
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不应该使用
WithConstructorArgument
;相反,为 ISession 创建绑定。您可以从
context.Request.ParentRequest.Service
获取IRepository
类型。您现在可以使用反射提取实体类型。但是,如果您对所有实体使用相同的数据库,那么为所有存储库返回常规会话可能会更容易。You should'nt use
WithConstructorArgument
; create a binding for ISession instead.You can get the
IRepository<>
type fromcontext.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.