Can anyone point me in the direction of some samples or instructions on how to achieve this please?
Asked
Active
Viewed 3,873 times
5
-
Full code is available here: http://stackoverflow.com/a/27244289/351204 – Pouya Barrach-Yousefi Dec 03 '14 at 16:11
2 Answers
9
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)

trailmax
- 34,305
- 22
- 140
- 234
-
1This is what I had thought it would be but it throws an error as the HttpContext.Current.GetOwinContext().Authentication is null. – wmcainsh Sep 02 '14 at 15:40
-
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` – trailmax Sep 02 '14 at 15:58
-
-
-
I don't. Where should I be initializing my container so that the OwinContext is present? – wmcainsh Sep 04 '14 at 08:31
-
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? – trailmax Sep 04 '14 at 09:27
-
1Also 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: http://stackoverflow.com/a/6567855/809357 – trailmax Sep 04 '14 at 09:33
-
-
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. – trailmax Sep 04 '14 at 13:41
-
It was as simple as: For
().Use – wmcainsh Sep 04 '14 at 15:11(() => new MyAuthenticationManager(HttpContext.Current.GetOwinContext().Authentication));
8
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

wmcainsh
- 161
- 1
- 6