Can anyone point me in the direction of some samples or instructions on how to achieve this please?
asp.net identity 2.1 injecting IAuthenticationManager using StructureMap
Asked Answered
Full code is available here: https://mcmap.net/q/1023960/-how-to-configure-asp-net-identity-applicationusermanager-with-structuremap –
Croissant
I have not used StructureMap, but I have done this with Autofac and SimpleInjector.
Autofac registration would look like this:
builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As<IAuthenticationManager>();
Registration in SimpleInjector looks like this:
container.RegisterPerWebRequest(() => HttpContext.Current.GetOwinContext().Authentication);
And from looking on StructureMap tutorial I can guess that registration there would be something like this:
ForRequestedType<IAuthenticationManager>()
.TheDefaultIs(() => HttpContext.Current.GetOwinContext().Authentication)
This is what I had thought it would be but it throws an error as the HttpContext.Current.GetOwinContext().Authentication is null. –
Selene
This means you are trying to resolve
IAuthenticationManager
before there OwinContext
is created for the request. Usually this happens when you try to resolve it without http-request, i.e. in Global.asax
–
Mckee That is the problem, where should I be doing this? –
Selene
Why do you need
IAuthenticationManager
before the request happens? –
Mckee I don't. Where should I be initializing my container so that the OwinContext is present? –
Selene
mm.. only reason I can think of is that container resolving objects in Global.asax, and one of the resolved objects needs
IAuthenticationManager
. This caught me once as well, I needed UserManager
in Global.asax
to make sure Admin user is created. And UserManager
was dependent on IAuthManager
. Are you not doing something like this? –
Mckee Also there is a chance that StructureMap creates all the instances on registration and tries to resolve
IAuthManager
at the same time. Try doing late resolving. Something like this answer: https://mcmap.net/q/1921653/-register-a-default-instance-in-structuremap –
Mckee Thanks, that post helped a lot. –
Selene
Good! Can you post your solution as an answer please. I did struggle with this very issue, would be good if the solution is available to the community. –
Mckee
It was as simple as: For<IAuthenticationManager>().Use<MyAuthenticationManager>(() => new MyAuthenticationManager(HttpContext.Current.GetOwinContext().Authentication)); –
Selene
This initially came about by converting Identity to use int as the unique key values as described here.
I then extended this and created a custom AuthenticationManager using IAuthenticationManager.
I then setup StructureMap as follows:
For<IAuthenticationManager>()
.Use<MyAuthenticationManager>(
() => new MyAuthenticationManager(HttpContext.Current.GetOwinContext().Authentication));
Thanks @trailmax
Nice solution. Decorator for the win! –
Mckee
© 2022 - 2024 — McMap. All rights reserved.