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.

Follow

Get every new post delivered to your Inbox.