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);
}

Thursday, July 2, 2015

Post vs Put vs Patch in Web API

 Debates rages on and on. Why, when and how.
 My 2 cents:

  1. POST- create if you don't know resource location, but leaving it to the server to determine it and send back location of new resource to you in the header.
  2. PUT - hm, it should really be called replace. It should either create resource on specified url (by client!) or completely update it, no partial updates here.
  3. PATCH - intended for partial updates, not really available yet.
  4. POST - update - tricky one. Since we don't have PATCH yet that's the only alternative for partial updates as of now.

So something like this for POST:

// POST: api/Items
[ResponseType(typeof(BudgetItem))]
public IHttpActionResult Post(BudgetItem item)
 {
   if (ModelState.IsValid)
     {
        _itemRepository.CreateItem(item);
        return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
     }
   else
      {
      return BadRequest(ModelState);
      }
  }


And for PUT:

// PUT: api/Items/5
public IHttpActionResult Put(int id, BudgetItem item)
  {
     if (!ModelState.IsValid)
       {
           return BadRequest(ModelState);
        }
     BudgetItem oldItem = _itemRepository.GetItem(id);
     if (oldItem == null)
        {
           _itemRepository.CreateItem(item);
           return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
        }
      else
       {
          _itemRepository.UpdateItem(item);
          return Ok(item);
       }
   }