Unity equivalent for Ninject's Bind.ToMethod of IPrincipal,IIdentity
Asked Answered
L

3

6

I'm trying to replicate the following Ninject syntax in Unity, but not having any luck:

Bind<IIdentity>().ToMethod(c => HttpContext.Current.User.Identity);

I'm thinking it ought to look something like:

IUnityContainer container;
...
container.RegisterType<IIdentity>(HttpContext.Current.User.Identity);

How should it be?

Longoria answered 23/11, 2011 at 17:43 Comment(0)
C
11

While neontapir's answer could work, that extension method is Obsolete. The correct way to do this now would be to use an InjectionFactory:

container.RegisterType<IIdentity>(new InjectionFactory(u => HttpContext.Current.User.Identity));
Chauncey answered 23/11, 2011 at 18:1 Comment(0)
A
1
container.RegisterInstance<IIdentity>(...);
Aspirin answered 23/11, 2011 at 17:50 Comment(4)
This wouldn't work as it would capture the current instance of User.Identity, and always return that. The OP wants the User.Identity to be evaluated every time the container is asked to resolve an IIdentity.Chauncey
True. If the exact semantics is required then your answer is obviously closer to this.Aspirin
HttpContext.Current.User.Identity isn't available when the container is initialized, so yes wanted it to be evaluated each time.Longoria
The key is you want: () => HttpContext.Current.User.Identity NOT HttpContext.Current.User.IdentityZavras
S
0

I believe a static factory extension would do it. I'm rusty on Unity. Seeman's Dependency Injection in .NET is a good resource for situations like this.

Sha answered 23/11, 2011 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.