问题描述
当尝试手动创建DataProtectionProvider
时,我偶然发现Microsoft文档对 DpapiDataProtectionProvider
其中表示:
When trying to create a DataProtectionProvider
manually I have stumbled upon the Microsoft documenation to DpapiDataProtectionProvider
which says:
突然出现一个问题:当您的应用程序由ASP.NET托管时,最佳选择是什么?
进一步搜索,似乎最好的选择是从OWIN获得DataProtectionProvider
.这可以在启动配置中完成,在该配置中,您具有IAppBuilder
并使用位于Microsoft.Owin.Security.DataProtection
名称空间中的AppBuilderExtensions
可以调用app.GetDataProtectionProvider()
.
Searching further, it seems the best choice is to obtain the DataProtectionProvider
from OWIN. That can be done in Startup configuration, where you have IAppBuilder
and using AppBuilderExtensions
located in Microsoft.Owin.Security.DataProtection
namespace you can call app.GetDataProtectionProvider()
.
到目前为止,我很满意.但是,现在您想将DataProtectionProvider
注入类的构造函数中(例如UserManager
).我已经看到一个建议,您可以在其中存储DataProtectionProvider
设置为静态属性,然后在需要的地方使用它,但这似乎是一个相当错误的解决方案.
So far, I am quite satisfied. However, now you want to inject the DataProtectionProvider
in a constructor of your class (e.g. a UserManager
). I have seen one suggestion where you store the DataProtectionProvider
in a static property and then use it where you need, but that seems like a rather wrong solution.
我认为类似于以下代码的解决方案将是适当的(使用ninject容器):
I think a solution similar to the following piece of code would be appropriate (using ninject container):
kernel.Bind<IDataProtectionProvider>()
// beware, method .GetDataProtectionProvider() is fictional
.ToMethod(c => HttpContext.Current.GetOwinContext().GetDataProtectionProvider())
.InRequestScope();
推荐答案
有一个演练,它告诉您如何向Autofac注册DataProtectionProvider.
There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
这篇关于在MVC 5中获取DataProtectionProvider以正确进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!