在 MVC 5 中获取 DataProtectionProvider 以正确进行依赖注入

San*_*hos 6 asp.net-mvc dependency-injection owin owin-security

在尝试DataProtectionProvider手动创建时,我偶然发现了 Microsoft 文档,DpapiDataProtectionProvider其中说:

用于提供派生自数据保护 API 的数据保护服务。当您的应用程序不是由 ASP.NET 托管并且所有进程都以相同的域标识运行时,它是数据保护的最佳选择

突然出现一个问题:当您的应用程序由 ASP.NET 托管时,最佳选择什么?

进一步搜索,似乎最好的选择是DataProtectionProvider从 OWIN获取。这可以在启动配置中完成,您可以在命名空间中IAppBuilder使用和使用AppBuilderExtensionsMicrosoft.Owin.Security.DataProtection您可以调用app.GetDataProtectionProvider().

到目前为止,我很满意。但是,现在您想将 注入到DataProtectionProvider您的类的构造函数中(例如 a UserManager)。我看到了一个建议,你将它存储DataProtectionProvider在一个静态属性中,然后在你需要的地方使用它,但这似乎是一个相当错误的解决方案。

我认为类似于以下代码段的解决方案是合适的(使用 ninject 容器):

kernel.Bind<IDataProtectionProvider>()
    // beware, method .GetDataProtectionProvider() is fictional
    .ToMethod(c => HttpContext.Current.GetOwinContext().GetDataProtectionProvider())
    .InRequestScope();
Run Code Online (Sandbox Code Playgroud)

Nig*_*888 6

有一个演练告诉您如何向 Autofac 注册 DataProtectionProvider。

builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
Run Code Online (Sandbox Code Playgroud)