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

我已经制作了一个简单的OWIN中间件,它将为我提供一个User对象并将其添加到HttpContext.Current.Items中,以便每个请求的所有控制器和视图都可用.

这是我的代码

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注入为依赖项?这有可能吗?

解决方法

根据 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);
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....