【问题标题】:Use Ninject DI inside my own OWIN middleware在我自己的 OWIN 中间件中使用 Ninject DI
【发布时间】:2014-07-09 17:35:22
【问题描述】:

我制作了一个简单的 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 作为依赖项注入?这可能吗?

【问题讨论】:

  • 您是否选择了任何实现。我也有这个问题
  • 我希望我不是在做一个愚蠢的问题,但是您是否尝试将其绑定到您的 IoC/DI 容器中? Bind<IContextManager>().To<ContextManager>();

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


【解决方案1】:

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

【讨论】:

  • 确保使用 Ninject Owin 包,如下所示github.com/ninject/Ninject.Web.Common/wiki/…
  • 当我这样做时,我在要注册中间件的行出现异常 (app.use()) 附加信息:类 'InCube.DigitalAdvisory.WebApi.LoggingMiddleware'没有带 1 个参数的构造函数。
【解决方案2】:

聚会有点晚了,但如果其他人偶然发现,我只是想帮忙。

我假设您正在Startup.cs 中注册您的自定义中间件。类似于app.Use<SetCurrentUserMiddleware>();

注意app.Use<T>() 接受额外参数为args[],这意味着你可以这样做

//example using AutoFac
app.Use<SetCurrentUserMiddleware>(container.Resolve<IUserRepository>());

在构建中间件时,额外的参数将作为任何额外的构造函数参数提供给中间件。

【讨论】:

    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多