Welcome...



...All those moments will be lost in time, like tears in rain....

- soliloquy from Blade Runner


Bits and bytes do get lost, awash in the rain of data flow that is Internet. They slip away from us, never to found again... some of them will be captured here, many more will not... like tears in rain...



Thursday, July 9, 2015

Setting up Autofac

 Autofac is very nice DI container, but documentation on their site is lacking on specifics.
 This is how I set up Autofac in global.asax.cs:


  protected void Application_Start()
   {
     RegisterAutofac();

     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
      
  }



and then do registration of all the things you want injected:

private void RegisterAutofac()
 {
   var builder = new ContainerBuilder();
   var config = GlobalConfiguration.Configuration;
   // all controllers are going to be built by autofac
   builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
   // concrete implementation first, interface second
   builder.RegisterType<ItemRepository>().As<IItemRepository>();

   //
   var container = builder.Build();
   config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

No comments:

Post a Comment