在MVC 5中获取DataProtectionProvider以正确进行依赖注入 [英] Get DataProtectionProvider in MVC 5 for dependecy injection correctly

查看:227
本文介绍了在MVC 5中获取DataProtectionProvider以正确进行依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试手动创建DataProtectionProvider时,我偶然发现Microsoft文档对

When trying to create a DataProtectionProvider manually I have stumbled upon the Microsoft documenation to DpapiDataProtectionProvider which says:

用于提供从 数据保护API. 这是您进行数据保护时的最佳选择 应用程序不是由ASP.NET托管的,并且所有进程都以 相同的域标识.

Used to provide the data protection services that are derived from the Data Protection API. It is the best choice of data protection when you application is not hosted by ASP.NET and all processes are running as the same domain identity.

突然出现一个问题:当您的应用程序由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();

推荐答案

有一个

There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.

builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();

这篇关于在MVC 5中获取DataProtectionProvider以正确进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆