asp.net-mvc - 在我自己的 OWIN 中间件中使用 Ninject DI

标签 asp.net-mvc dependency-injection owin ninject

我制作了一个简单的 OWIN 中间件,它将获取一个 User 对象并将其添加到 HttpContext.Current.Items 中,以便每个请求的所有 Controller 和 View 都可以使用它。

这是我的代码:

public class SetCurrentUserMiddleware : OwinMiddleware
{
    public SetCurrentUserMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public override Task Invoke(IOwinContext context)
    {
        if (context.Request.User.Identity.IsAuthenticated)
        {
            // Do some work to get a userId... (omitted)
            var repo = new UserRepository();
            User user = repo.Get(userId);
            HttpContext.Current.Items["CurrentUserContext"] = user;
        }

        return Next.Invoke(context);
    }
}

我在我的 Web 应用程序中使用 Ninject - 如何重构这个中间件,以便将我的 UserRepository 作为依赖项注入(inject)?这有可能吗?

最佳答案

根据this page ,您可以只提供自己的构造函数参数。

public class SetCurrentUserMiddleware : OwinMiddleware
{
    private readonly IUserRepository userRepository;

    public SetCurrentUserMiddleware(OwinMiddleware next, IUserRepository userRepository) : base(next)
    {
        if (userRepository == null)
            throw new ArgumentNullException("userRepository");
        this.userRepository = userRepository;
    }

    public override Task Invoke(IOwinContext context)
    {
        if (context.Request.User.Identity.IsAuthenticated)
        {
            // Do some work to get a userId... (omitted)
            User user = this.userRepository.Get(userId);
            HttpContext.Current.Items["CurrentUserContext"] = user;
        }

        return Next.Invoke(context);
    }
}

关于asp.net-mvc - 在我自己的 OWIN 中间件中使用 Ninject DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23777042/

相关文章:

asp.net - 在 ASP.NET MVC 中使用/Owin 授权静态文件

c# - 在 ASP.NET MVC 中设置包含连字符的 html 属性时出现问题

c# - 在查询字符串中使用点 ("."时未设置 CORS header )

dependency-injection - DI 容器可以用作 session 状态的替代吗?

asp.net-mvc - SignalR 2.X.X 的 Context.User.Identity.Name 为 null。如何修复它?

c# - 如何将参数传递给我自己的 Startup 类?

javascript - 通过缩小和 require.js 进行 MVC 捆绑

c# - SmtpClient.SendMailAsync 在抛出特定异常时导致死锁

java - 如何使用 guice 注入(inject)通用接口(interface)实现

java - Spring boot - 在测试中注入(inject)的存储库映射为空