问题
When trying to create a DataProtectionProvider
manually I have stumbled upon the Microsoft documenation to DpapiDataProtectionProvider which says:
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.
A question suddenly arises: What is the best choice when your application IS hosted by ASP.NET?
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()
.
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.
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();
回答1:
There is a walkthrough that tells you how to register the DataProtectionProvider with Autofac.
builder.Register<IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();
回答2:
You can also achieve this with Unity with the following line:
container.RegisterType<IDataProtectionProvider>(new InjectionFactory(c => app.GetDataProtectionProvider()));
Where container is
var container = new UnityContainer();
This will allow you to use the DataProtectionProvider in the constructor as follows.
public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService, IDataProtectionProvider dataProtectionProvider)
I prefer this approach over the approach mentioned on this blog post here https://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/, simply because it allows you to have the classes that use the DataProtectionProvider in separate libraries if you would like and it is much cleaner.
来源:https://stackoverflow.com/questions/36473209/get-dataprotectionprovider-in-mvc-5-for-dependecy-injection-correctly