ASP.NET Web API and Unity

In my last post, I walked through the relatively simple task of adding Ninject to ASP.NET Web API.  I’ve been looking at solving some common problems like logging and caching in an Aspect Oriented Programming approach.  So I’ve been looking into Interceptors and how they can help implement AOP.  More on this later.  I thought I’d take a look at Unity from Microsoft’s Patterns & Practices group because it supports IoC and Interceptors.  As Scott Hanselman points out, there are a lot of frameworks for this and I just chose Unity to get started.

So what does it take to swap out Ninject with Unity?  Very little as it turns out.  There’s a minor modification to the IDependencyResolver implementation that uses the IUnityContainer instead of IResolutionRoot.  Here’s what the code originally looked like with Ninject:

public class NinjectDependencyResolver : System.Web.Http.Services.IDependencyResolver
{
    private readonly IResolutionRoot resolutionRoot;

    public NinjectDependencyResolver(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }

    public object GetService(Type serviceType)
    {
        var service = resolutionRoot.TryGet(serviceType);

        return service;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        var services = resolutionRoot.GetAll(serviceType);

        return services;
    }
}

And here’s what it looks like using Unity:

public class UnityDependencyResolver : System.Web.Http.Services.IDependencyResolver
{
    private readonly IUnityContainer container;

    public UnityDependencyResolver(IUnityContainer container)
    {
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        object service = null;

        if (!container.IsRegistered(serviceType))
        {
            if (serviceType.IsAbstract || serviceType.IsInterface)
            {
                return service;
            }
        }

        service = container.Resolve(serviceType);

        return service;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        IEnumerable<object> services = container.ResolveAll(serviceType);

        return services;
    }
}

After that, I made a minor modification to RegisterDependencies.  Really, it’s pretty much just a syntax change from Ninject’s Bind to Unity’s RegisterType.  Here’s what the code originally looked like with Ninject:

public class WebApiApplication : System.Web.HttpApplication
{
    public static void RegisterDependencies()
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<ISomeService>().To<SomeService>();

        var ninjectResolver = new NinjectDependencyResolver(kernel);

        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(ninjectResolver);
    }

    protected void Application_Start()
    {
        RegisterDependencies();

        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
        RegisterGlobalFilters(GlobalFilters.Filters);
            
        BundleTable.Bundles.RegisterTemplateBundles();
    }
}

And here’s what it looks like using Unity:

public class WebApiApplication : System.Web.HttpApplication
{
    public static void RegisterDependencies()
    {
        IUnityContainer container = new UnityContainer();

        container.RegisterType<ISomeService, SomeService>();

        var unityResolver = new UnityDependencyResolver(container);

        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(unityResolver);
    }

    protected void Application_Start()
    {
        RegisterDependencies();

        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
        RegisterGlobalFilters(GlobalFilters.Filters);
            
        BundleTable.Bundles.RegisterTemplateBundles();
    }
}

I was really happy with how easy it was to swap out IoC frameworks.  Even more reason why you should just pick one and get started.  There’s no excuse to not use IoC to elegantly resolve dependencies.

ASP.NET Web API and Ninject

The ASP.NET Web API beta just released as part of the MVC 4 beta.  The Web API is geared towards making it really easy to create and expose APIs that can be accessible from a variety of clients including mobile.  If you’ve had any experience with creating RESTful services using WCF or the WCF Web API then you’ll be as thrilled about the promises of the ASP.NET Web API as I am.

Ninject was always a pain in WCF RESTful services.  There were some extensions to Ninject that were aimed at making this easier but I never really liked the experience.  I ended up abandoning Ninject in my WCF RESTful services so I was pretty exciting about getting it back as part of ASP.NET Web API.  Thankfully, this ended up being really easy to do.

MVC has a built in dependency resolver which makes plugging in Ninject really easy to do (compared to custom ServiceHostFactories in WCF).  First up, we need to create a class that implements IDependencyResolver.

public class NinjectDependencyResolver : System.Web.Http.Services.IDependencyResolver
{
    private readonly IResolutionRoot resolutionRoot;

    public NinjectDependencyResolver(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }

    public object GetService(Type serviceType)
    {
        var service = resolutionRoot.TryGet(serviceType);

        return service;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        var services = resolutionRoot.GetAll(serviceType);

        return services;
    }
}

Next, we need to tell MVC that we’re using this custom dependency resolver. We do this in the Global.asax.

public class WebApiApplication : System.Web.HttpApplication
{
    public static void RegisterDependencies()
    {
        IKernel kernel = new StandardKernel();

        kernel.Bind<ISomeService>().To<SomeService>();

        var ninjectResolver = new NinjectDependencyResolver(kernel);

        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(ninjectResolver);
    }

    protected void Application_Start()
    {
        RegisterDependencies();

        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
        RegisterGlobalFilters(GlobalFilters.Filters);

        BundleTable.Bundles.RegisterTemplateBundles();
    }
}

If you’re familiar with Ninject we create the StandardKernel, specify the bindings and then pass it to our dependency resolver. And that’s it.  Relatively simple to add Ninject to ASP.NET Web API.

Kinect for Windows Available

Kinect for Windows is now Available! I was pretty excited when I first heard Microsoft was releasing an SDK. Obviously it’s innovative and cool technology, but it’s even more interesting in what we’ll see out of the community that we haven’t even thought of yet. Good for Microsoft for opening up the creative floodgates.

Take a look and I can’t wait to see what you come up with.

Netflix Open Sources Their Cassandra Client

As you probably know, I’m a big fan of Netflix as a company and their technical approach. They’ve just open sourced their Cassandra client known as Astyanax.

If you’re using (or thinking about using Cassandra) then take a look and let me know what you think.

http://techblog.netflix.com/2012/01/announcing-astyanax.html

The Future Of HTPCs Isn’t Bright

Recently, Boxee announced that after the upcoming 1.5 software release in January, they will no longer release versions for the PC/Mac/Ubuntu. They also make a hardware appliance similar to the Apple TV known as the Boxee Box. You see, they believe the future of TV are these devices and not HTPCs. Having owned an HTPC and now an Apple TV, I couldn’t agree more.

I built a Home Theatre PC (HTPC) running Windows 7 and a variety of HTPC software (Boxee included). I settled on Windows Media Center with a few different plug-ins. But I’ll be honest, the experience sucked! It always felt like I was running software on Windows on my TV. Crashes, bouncing back and forth between Media Center and the Desktop because Media Center was way too limited and a host of other very desktop like experience. This worked okay for me because I’m a techie and my tolerance for this kind of thing is pretty high. But for my family, they hated it so much that they got to the point where they refused to use it because it was too much of a pain. I took steps to help make things easier and more functional, but it was just a lackluster experience.

I switched over to Apple TV because it just works. You can stream video, music and the entire display from either our iPhones or iPad. It doesn’t handle my digital DVD collection (legit) well but that turned out to be a feature we don’t really miss that much. Music isn’t ideal because we have to stream it from an iPhone or iPad which makes control a bit of a pain (hopefully iTunes Match will resolve this). Of course, it is focused on renting and buying movies & TV shows, and watching Netflix / other internet content. And these things it does really well.

Even Microsoft no longer believes in HTPCs as its Windows Media Center application is woefully behind pretty much anything else out there and doesn’t seem to be significantly enhanced much these days. Instead, they’ve focused their Home Theatre approach to the XBox. The thought of controlling my TV experience with gestures and voice via Kinect was almost enough for me to go buy an XBox (ultimately didn’t because I don’t play video games at all so it seems a waste). Siri could give the Apple TV an edge over some of it’s competitors. And of course, the alleged next gen Apple TV could be another game changer if Steve Jobs truly did “crack it.”

We’ll have to see who comes out ahead by creating a truly innovative TV experience. It’s safe to say that it won’t be the HTPC…I’ve got one for sale if you’re unconvinced.

The New Windows Azure Billing Portal Brings a Tear of Joy to My Eyes

If you’ve ever had the “pleasure” of working with the old Windows Azure Billing Portal, I’m sure you’ll agree that it’s a psychological experiment on the most effective way to increase blood pressure through poor UI.  Luckily, the Microsoft team has released a new portal for billing.  And I have to say, this is way more along the lines of what I was originally hoping for. 

You still find it through the Billing link in the upper right corner of the Azure Portal.

image

You’ll then be treated to a very metro style portal.

image

Let’s take a moment to reflect on the pure beauty here.  There’s an easy to see (large) total estimated billing amount.  And you can see each of the common billing areas (like AppFabric Cache) with total used against how much is provided with your plan.  Pure genius!!  I can easily see what I’ve used from my MSDN benefits and I can see the Pay-As-You-Go stuff down at the bottom.  This whole easy to find information is in stark contrast to the old billing portal.

I love it!!  Nice job Microsoft.

* Update 12/13/2011 *

Here’s an example of what the old billing portal looked like:

image

Windows Home Server 2011 – Backup Plan

As part of my Windows Home Server 2011 Custom Build (Part1 and Part2), I wrote about what the hardware looks like and how I set up my drives.  In the last part of this series I’ll cover the Backup and Restore strategy. 

While I like remote access, the main reason I actually got a WHS was to ensure that my data stays safe no matter what.  Lost data is the kind of horror that can break up a marriage (especially true with our first baby now part of the family).  I wanted something that gave me piece of mind, wouldn’t require me spending an entire weekend to recover everything if things went south, and preferably added a few other bells and whistles to make digital life even better. 

Like any good backup strategy, I want to cover as many different disaster scenarios applying the right solution to each problem. 

BriscoeBackupStrategy2011

So each computer in the house backs up to WHS which makes it easy to restore the computer in case of a hardware crash.  My WHS includes RAID to help with hardware failure,  However, I’m also backing up to external USB drives, twice daily just in case so that it’s easier to restore WHS 2011.  Then nightly, the entire WHS is backed up to the cloud using CrashPlan to handle serious disasters like a fire (or more recently tornados).  The fire safe backup is kind of a legacy thing, but I’m thinking with the cloud based backup that I don’t need to back up to the fire safe anymore.  What do you think?

A quick note on the cloud backup.  I really wanted to use something like KeepVault or CloudBerry backup because they offer native WHS 2011 plug-ins which I think is a nice feature.  However, the price point compared to CrashPlan just didn’t work out.  I’m hopeful that CrashPlan starts officially supporting WHS 2011 and offers a plug-in in the near future.  I will also only be backing up really important stuff like pictures to help keep my storage down.  CrashPlan has unlimited storage so that’s more to conserve bandwidth.  Plus, in the event of a complete disaster like my house is taken to Oz then I won’t be that concerned with stuff I can replace like my movies.

Let me know what you think and if there’s a better way I can do this.  Until I hear something better, the strategy I outlined is what I’m sticking with and I’ll post an update when disaster strikes.

In addition to blogging, I’m also using Twitter for quick updates.  @seanbriscoe.

The Ultimate Developer Machine Contest…At Work!

You may have heard of the Ultimate Developer Machine competition between Scott Hanselman and Pete Brown in which they competed against each other to build a machine with a 7.9 Windows Experience Index score.  I recently put together a new developer machine, a server and a Windows Home Server with decent results.  I’m definitely a fan of building my own machines as I think it’s fun and it’s a nice way to customize for your specific needs.

However, I was absolutely thrilled that the CIO of the company I work for decided to host a work sponsored “Build the Ultimate Rig” contest.  With a $1,500 budget, pizza party run-off, prizes and getting to use the machine when we’re done, it’s a great way to help foster a fun work environment.  Plus, how many times have you complained about the standard piece of garbage companies hand out to their developers (if you’re like me, then the answer is “a lot”)?  This is a chance for us to put our money where our mouth is and build something we really enjoy working with. 

Here’s the part list I came up with (no over-clocking or water-cooling allowed):

Qty Product Price
1 NZXT Phantom PHAN-001BK Black Steel / Plastic Enthusiast ATX Full Tower Computer CaseNZXT Phantom PHAN-001BK Black Steel / Plastic Enthusiast ATX Full Tower Computer Case $139.99
1 EVGA SuperClocked GeForce GTX 560 Ti (Fermi) 01G-P3-1563-AR Video CardEVGA SuperClocked 01G-P3-1563-AR GeForce GTX 560 Ti (Fermi) 1GB 256-bit GDDR5 PCI Express 2.0 x16 HDCP Ready SLI Support … $259.99
1 Antec EA750 750W Continuous Power Antec EarthWatts EA750 750W Continuous Power ATX12V version 2.3 SLI Certified CrossFire Ready 80 PLUS Certified Active PFC … $89.99
1 G.SKILL Ripjaws X Series 8GB (2 x 4GB) 240-Pin DDR3 SDRAM DDR3 1600 (PC3 12800) Desktop MemoryG.SKILL Ripjaws X Series 8GB (2 x 4GB) 240-Pin DDR3 SDRAM DDR3 1600 (PC3 12800) Desktop Memory Model F3-12800CL8D-8GBXM $99.99
1 GIGABYTE GA-P67A-UD3-B3 ATX Intel MotherboardGIGABYTE GA-P67A-UD3-B3 LGA 1155 Intel P67 SATA 6Gb/s USB 3.0 ATX Intel Motherboard $129.99
1 Intel Core i7-2600 3.4GHz LGA 1155 95W Quad-Core Desktop ProcessorIntel Core i7-2600 Sandy Bridge 3.4GHz (3.8GHz Turbo Boost) LGA 1155 95W Quad-Core Desktop Processor BX80623I72600 $299.99
1 Crucial RealSSD C300 CTFDDAC064MAG-1G1 2.5Crucial RealSSD C300 CTFDDAC064MAG-1G1 2.5″ 64GB SATA III MLC Internal Solid State Drive (SSD) $144.99
1 OCZ Vertex 3 Series – MAX IOPS Edition VTX3MI-25SAT3-120G 2.5OCZ Vertex 3 Series – MAX IOPS Edition VTX3MI-25SAT3-120G 2.5″ 120GB SATA III MLC Internal Solid State Drive (SSD) $319.99
  Subtotal $1484.92
  Shipping $10.23
  Grand Total $1495.15

* Images are courtesy of Newegg *

As you can see, I slid in right under the $1,500 limit.  Like all things, I had to make some trade-offs to hit my budget but I tried to make good decisions based on what I learned from previous builds.

For instance, I wanted to get a second OCZ SSD (have you seen the read/write rates on this thing?!?) but couldn’t make that work so I settled for a slower second SSD that I will put my main applications on (like Visual Studio).  I wanted to try RAID0 with SSDs but that was too expensive.  I also wanted to get a third drive that was a large data drive, but again I’m right at the limit so it was one of the things to go.  Same went for the i7-2600 instead of the i7-2600k (or even better the i7-980X for a mere $1k).  I splurged on the case because if cases could look hot, this one would be smoking.  I also upped the video card (even though the i7-2600 comes with built in HD) because I didn’t want the graphics to limit my WEI score.

I’m positive that this machine will be a blast to work with on a daily basis, and I’m hopeful that I’ll be respectable in the competition.  Let me know what you think of the build or where you think I could have made better trade-offs.

If you’re interested in working at a company that has these kind of fun events and treats their developers like valued members of the organization, please email me at sean.briscoe@inmar.com (or tweet @seanbriscoe) as we are always looking for talented developers willing to work in Winston-Salem, NC.

WP7 – Official Fix for Walshed Phones

Chris Walsh has posted an official fix to get you back on the upgrade path if you applied his earlier NoDo update hack.  This fix has been tested by Brandon Watson and his team so you should be good to go.

Having previously Walshed my phone, I applied this fix and it successfully updated.  The first time I ran it, the tool crashed waiting for the phone to reboot.  However, I rebooted my computer and my phone, ran the update again and it then updated successfully.

As usual, AT&T appears to be behind on the updates as I still haven’t received the security update.  Once I do, I’ll post an update regarding how it went.

A big thanks to Chris for getting us back on track!!  I’d also like to point out that it’s fantastic that Brandon and his team worked with Chris to officially certify the fix.  It was originally an unsupported hack so Microsoft went out of their way to work with the community on this one.

Samsung Focus – Expansion card died after two months

My Samsung Focus ran out of batteries the other day and turned itself off.  I try to avoid this but it certainly wasn’t the first time it’s happened.  I plugged it back in and after fifteen minutes or so it powered back on.  But this time it came up with a message saying that my storage had changed, been damaged or removed and that I needed to fix it and restart the device.  Uh oh.

I tried rebooting, removing and reinserting the card and just about everything else I could think of…no dice.  The phone was unusable.  I then got desperate to avoid a painful trip to the AT&T store (where we struggle through basic things like opening the phone) and started down the hard reset path.  Reformat worked fine but same error when I started the phone again.  Ultimately I had to remove the expansion card and do another hard reset.

So I’m back to a mere 8 GB until I can get another replacement.  Sadly, the restore didn’t work either because I Walshied my phone or more likely because it no longer has 24 GB of space.  It would be really nice to restore things like settings and apps regardless of changes to the phone hardware.  Sure, if there wasn’t a space for the apps then I understand.  But having to reset every setting, email account, theme, etc seems like a pretty poor experience.

Pretty disappointing that the 16 GB Patriot class 10 card died exactly two months from original purchase.  Hopefully they’ll provide some good customer service around the card.

Create your own website, free on WordPress.com.Create your own website.
Start free