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?

neontapir
  • 4,698
  • 3
  • 37
  • 52
Alfred
  • 800
  • 8
  • 16

3 Answers3

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));
Community
  • 1
  • 1
BFree
  • 102,548
  • 21
  • 159
  • 201
1
container.RegisterInstance<IIdentity>(...);
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • 1
    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. – BFree Nov 23 '11 at 18:02
  • True. If the exact semantics is required then your answer is obviously closer to this. – Wiktor Zychla Nov 23 '11 at 18:05
  • 1
    HttpContext.Current.User.Identity isn't available when the container is initialized, so yes wanted it to be evaluated each time. – Alfred Nov 23 '11 at 20:05
  • The key is you want: () => HttpContext.Current.User.Identity NOT HttpContext.Current.User.Identity – Tod Thomson Feb 13 '13 at 05:59
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.

neontapir
  • 4,698
  • 3
  • 37
  • 52