Ninject 在 ToMethod 中获取泛型类型

发布于 2024-12-07 23:47:38 字数 743 浏览 0 评论 0原文

我有一个像这样的存储库:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长不大的小祸害 2024-12-14 23:47:38

您不应该使用 WithConstructorArgument;相反,为 ISession 创建绑定。

kernel.Bind<ISession>.ToMethod(context => ....).InRequestScope();

您可以从 context.Request.ParentRequest.Service 获取 IRepository 类型。您现在可以使用反射提取实体类型。但是,如果您对所有实体使用相同的数据库,那么为所有存储库返回常规会话可能会更容易。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文