Wednesday, November 26, 2008

An ASP.NET MVC helper for calling Autofac Resolve


   1: // Typical Autofac integration with ASP.NET MVC
   2: public class MvcApplication : System.Web.HttpApplication, IContainerProviderAccessor
   3: {
   4:         public IContainerProvider ContainerProvider
   5:         {
   6:             get
   7:             {
   8:                 return _containerProvider;
   9:             }
  10:         }
  11: }
  12:  
  13: // Our Resolve Extension Method
  14: public static class AutofacHelper
  15: {
  16:     public static T Resolve <T> (this HttpContext source)
  17:     {
  18:         IContainerProviderAccessor cpa = (IContainerProviderAccessor)source.ApplicationInstance;
  19:         return cpa.ContainerProvider.RequestContainer.Resolve<T> ();
  20:     }
  21: }
  22:  
  23: // Resolving easy-mode
  24: ICustomerService customerService = HttpContext.Current.Resolve<ICustomerService> ();
  25:  
  26: // Example code-behind
  27: public partial class Site : System.Web.Mvc.ViewMasterPage
  28: {
  29:     protected string GetUserName ()
  30:     {
  31:         if (Request.IsAuthenticated)
  32:         {
  33:             ICustomerService customerService = HttpContext.Current.Resolve<ICustomerService> ();
  34:             Customer customer = customerService.GetCustomer (HttpContext.Current.User.Identity.Name);
  35:             if (customer != null && customer.IsRegistered)
  36:             {
  37:                 return customer.FirstName + " " + customer.LastName;
  38:             }
  39:         }
  40:  
  41:         return string.Empty;
  42:     }
  43: }