我已经制作了一个简单的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); } }