如何在ASP.NET MVC 5中将IAuthenticationManager与Ninject绑定?

Gup*_*R4c 15 c# asp.net-mvc ninject owin asp.net-mvc-5

我正试图IAuthenticationManager与Ninject 绑定,所以它可以注入我的AuthenticationService.问题是我目前IAuthenticationManagerHttpContext.GetOwinContext()我这里得到了Controller,就像这样:

private IAuthenticationManager AuthenticationManager {
    get {
        return this.HttpContext.GetOwinContext().Authentication;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何创建与Ninject的绑定,以便它知道IAuthenticationManagerHttpContext.GetOwinContext()运行时查找?可能吗?我的问题是否有意义?提前致谢!

Gup*_*R4c 31

所以,我明白了.Ninject提供HttpContext直接访问,所以我这样做:

kernel.Bind<IAuthenticationManager>().ToMethod(
    c =>
        HttpContext.Current.GetOwinContext().Authentication).InRequestScope();
Run Code Online (Sandbox Code Playgroud)

对于任何好奇的人来说,就是这样.

更新@Meep

因此,Ninject不必与MVC生活在同一个项目中.出于这个目的,我将它拉出到一个单独的项目中,在我的案例中称为"X.Dependencies".它引用了我需要实际设置绑定的所有其他项目,NuGet包等.它包含两个文件,Ninject在添加时创建的原始C#文件我已重命名为NinjectConfiguration,并且需要一个cheaty文件AssemblyReferences,以使Visual Studio实际将所有程序集导入主项目.这是它的代码:

/// <summary>
/// Cheaty way to force Visual Studio to find all assembly references, even the ones not directly used by the main project.
/// </summary>
internal static class AssemblyReferences {
    internal static readonly Type t1 = typeof(Ninject.Web.Mvc.MvcModule);
}
Run Code Online (Sandbox Code Playgroud)

现在,我想这可以避免,但到目前为止它对我有用.我很乐意接受建议.我只是从我的MVC项目添加对它的引用,让WebActivator负责初始化它,就像它使用常规方式一样.

我还把Owin拉进了它自己的名为"X.Owin"的项目中,它包含了通常的Owin启动类,我只是将其重命名为OwinConfiguration.

这两个都是我的"域层"的一部分,它还包含一些其他帮助项目.列表中另一个值得注意的项目是我的"X.Mappings",它用于配置AutoMapper映射.它还使用WebActivator进行自我初始化,所以我只是在MVC项目中添加对它的引用.

由于我从MVC项目中提取了大量代码,所以它在这一点上基本上都是路由和视图渲染.其他所有内容都会根据需要传递给帮助项目.