I am building a simple “single sign-on” ASP.NET application that interprets the current user’s ASP.NET integrated security credentials to a vendor site’s credentials. One of the services I wrote required the IIdentity as a constructor parameter to begin the interpretation process.
This was straightforward with regards to TDD – I simply mocked the IIdentity and kept going. When I began implementing dependency injection with an IoC container I struggled until I found a nice way to do this with Ninject.
Ninject offers a pretty cool suite of ASP.NET integration points in the Ninject.Framework.Web namespace. And without using System.Web.Abstractions, the best way I found to resolve a property of HttpContext.Current (User.Identity in my case) was to leverage a provider.
Update (6/25): Duncan Godwin, in the comments, explained what’s perhaps a better way to do this using ToFactoryMethod()
Ninject providers, IProvider and the simple implementation SimpleProvider<T>, allow the developer to customize the resolution of these hard-to inject objects. We’re talking providers today on the Ninject list.
Here’s the one I used to resolve IIdentity:
public class WebIdentityProvider : SimpleProvider<IIdentity> { protected override IIdentity CreateInstance(IContext context) { return HttpContext.Current.User.Identity; } public override bool IsCompatibleWith(IContext context) { return HttpContext.Current != null; } }
Here is sample code like I used in Global.asax.cs:
public class Global : NinjectHttpApplication { // ... protected override IKernel CreateKernel() { var module = new InlineModule( m => m.Bind<IIdentity>().ToProvider<WebIdentityProvider>(), m => m.Bind<IIdentityService>().To<IdentityService>(), m => m.Bind<IDisplayName>().To<DisplayName>() ); return new StandardKernel(module, new Log4netModule()); } }
When binding to the provider HttpContext.Current and the user’s IIdentity are available.
I have a feeling this isn’t the last one I’ll use.
Here is sample code with log4net’s AspNetTraceAppender turned on (using Ninject logging of course).
6 Responses
Arjan`s World » LINKBLOG for June 24, 2008
24|Jun|2008 1[...] Resolving HttpContext members using Ninject providers – Matt Hinze ‘ When I began implementing dependency injection with an IoC container I struggled until I found a nice way to do this with Ninject ‘ [...]
Duncan Godwin
24|Jun|2008 2Another way to do this is using the ToFactoryMethod(() => HttpContext.Current.User.Identity);
Matt
24|Jun|2008 3Ah, didn’t catch that one before. Good call Duncan.. =)
Dew Drop - June 25, 2008 | Alvin Ashcraft's Morning Dew
25|Jun|2008 4[...] Resolving HttpContext Members Using Ninject Providers (Matt Hinze) [...]
Interesting Links « QuantuMatrix’s Weblog
27|Jun|2008 5[...] Resolving HttpContext members using Ninject providers [Via: Matt ] [...]
Jesse
01|Dec|2009 6This is exactly what I was looking for. Thanks!
Leave a reply
Search
Categories
Archives
Links
Recent Posts
Tags
Copyright © 2008 - mhinze.com