Saturday, June 28, 2014

Dependency Injection Explained via JavaScript

When learning a new framework I often find it is useful to examine the source, use the framework, then go into a separate project and build the functionality from scratch to better understand the motivation behind the framework and what it may be saving me by using it. Angular is no exception. There are many tools in the AngularJS toolbox, from data-binding to compiling new HTML tags, but one of my favorites is the built-in dependency injection. You can browse Angular’s DI code here and read my blog posts about understanding Providers, Services, and Factories. A more advanced version is detailed in Interception using Decorator and Lazy Loading with AngularJS.

chimera3sm “Well, Dimitri, every search for a hero must begin with something every hero needs, a villain. So in a search for our hero, Bellerophon, we have created a more effective monster: Chimera.” – Dr. Nekhorvich, Mission Impossible II

I don’t believe I created a monster, but in my search to understand JavaScript dependency injection, I did create jsInject. This library acts as an dependency injection container for JavaScript components that depend on each other. It is based on constructor injection which inverts control of dependencies by passing them in through the constructor. If you are looking for dependency injection in JavaScript without taking on a full framework, this is an extremely lightweight solution that should do the trick for you.

For example, if your serviceA depends on dependencyB, you might define it like this to return it from a factory:

function serviceA(dependencyB) {
    return {
      id: dependencyB.getId()
    };
}

Another approach is to use a constructor function. This is required if you use a class-based approach, as code generated from tools like TypeScript doesn’t lend itself well to the factory pattern.

function ServiceA(dependencyB) {
    this.id = dependencyB.getId();
}

Of course there is always the self-invoking function as well:

var ServiceA = (function() {
    function ServiceA(dependencyB) {
        this.id = dependencyB.getId();
    }
    return ServiceA;
})();

In all of these cases, the dependency is injected and the purpose of a dependency injection container is to handle that injection for you.

Why Dependency Injection?

A logical first question is: why bother? I often hear this from developers and architects who are concerned that dependency injection adds unnecessary overhead and overcomplicates projects. More often than not they have worked on smaller projects with smaller teams and might not have run into the sheer size of project that benefits from dependency injection. I’m used to projects where there are tens of thousands if not hundreds of thousands of lines of client code (yes, I’m talking just the JavaScript part) with hundreds of components that interrelate. Forget module loading, bundling, etc. for a moment (worrying about how the scripts get loaded in the first place), let’s take a look at common problems:

  • When A depends on B and B depends on C, without dependency injection you create C from B and B from A and then reference A from a dozen different places. What happens when C now requires something, or B requires D in addition to C? Without dependency injection, that is a lot of refactoring and finding places you create those components. With dependency injection, A only has to worry about B. A doesn’t care what B depends on because that is handled by the DI container.
  • Timing is often an issue. What happens when A depends on B but the script for B is loaded after A? Dependency injection removes that concern because you can defer or lazy load the dependency when it’s time. In other words, regardless of how A and B are loaded, you only need to wire them up when you first reference A. On large projects when you have 50 JavaScript components referenced from a single page, the last thing you want to have to worry about is including them in the correct order.
  • Dependency injection is critical for testing. If A directly instantiates B then I’m stuck with the implementation of B that A chooses. If B is injected into A, I can create a “mock B” or a “stub B” for testing purposes. For example, you might have a component that depends on a web service. With dependency injection, you can create an implementation that uses hard-coded JSON for testing purposes and then wire in the real component that makes the service call at runtime.
  • Single Responsibility – Dependency Injection is actually one of the SOLID principles. It helps to encourage the notion of designing components with a Single Responsibility. You want to be able to focus on one thing in a component an should only have to change it for one reason. This is like building padding around your component, insulting the rest of the system. If the component is responsible for boiling water and mixing shakes, anytime you change it you have to test both scenarios. Having a single responsibility means you can change how you boil water without worrying about making shakes because another component is responsible. That makes it easier to maintain the code.
  • Psst … managers. Here’s something else to think about. Forget the technology, let’s talk about teams. When you have a lot of cooks in the kitchen, it is easy for them to bump elbows and step on each other’s toes. Having nice, isolated components means more team members can work in parallel without having to worry about what the other person is doing. I’ve witnessed this on many projects – again, if you have one component boil water and mix shakes, only one person can apply changes at a time. If you have two separate components, you can improve both scenarios at the same time.

hero I believe there are many benefits and that DI itself is only as complicated as you make it. In my experience, it simplifies things on larger projects.

Dependency Injection to the Rescue

The most basic DI solutions provide at least two features: the ability to register a component, and the ability to retrieve an instance of a component. Advanced solutions will allow you to intercept requests, override methods on the fly, register multiple components that satisfy a given interface and even manage the lifetime of a component (whether you get a new instance or the same one each time). The registration is key because that tells the container what you expect to retrieve, and somehow the container must also understand what dependencies to provide.

A naive implementation will use the constructor parameters to determine dependencies. I call this naive because naming a parameter doesn’t imply the dependent component has the same name, and when you minify or uglify your JavaScript code you lose information. A more common approach is to annotate the component somehow. I really like the options that Angular provides for annotations. When you register a component, you give it a name that doesn’t necessarily have to match the name of the constructor function or the function being called as a factory. When you annotate a component, you simply provide a list of names of dependencies. There are two ways to do this. You can either mark these up on the component itself by exposing a property as an array, or you can pass these in to the container when you register it.

Registering the Component

Let’s register a component. For jsInject I decided to mirror Angular’s approach and allow you to either pass dependencies at registration time, or use a static property. Here is an example of providing the information at registration time:

var fn = (function() {
   function Fn(echo) {
      this.echo = echo;
      this.test = function() {
         return echo.echo(expected);
      };
    }
    return Fn;
})();
$jsInject.register("1", ["echoFn", fn]);

In this case the dependency passed in as “echo” to the constructor is registered as “echoFn” to the container, and the function we are registering called fn is named “1” in the container. The registration expects an array. The last member should always be the component we are registering (whether it is a constructor function or factory) and the members before it are the names of the dependencies in the order they will be passed in.

The other approach is to annotate the component. Here is an example of using the annotation approach. This service exposes a hard-coded static property called $$deps to list the dependency names:

function ServiceB(serviceA) {
    this.id = serviceA.id + "b";
}
ServiceB.$$deps = ["ServiceA"];

It is registered like this (notice there are no “annotations” added to the registration array, just the constructor function itself):

$jsInject.register("ServiceA", [ServiceA]);

jsInject creates a method for instantiating the component but does not try to invoke it right away. It is a lazy-loading function. The first time the component is needed, it will instantiate it, then it will return the same copy for future requests. Here is the general pattern – we’ll expand the magic part, but note how once it’s done, it won’t go through that work again because the function replaces itself with a new one that simply returns the instantiated component.

var _this = this;
this.container[name] = function (level) {
    var result = {}; // magic goes here
    _this.container[name] = function () {
        return result;
    };
    return result;
};

So how exactly does it wire up the dependencies?

Retrieving the Component

The magic is in walking through the dependency chain. The algorithm itself is fairly simple. You basically iterate the list of annotations, grab them from the container recursively, and shove them into a list of arguments that you’ll pass to the component’s constructor. If an annotation has been instantiated, it is returned, otherwise it is also scanned for its own annotations and so forth. The trick is understanding the format of what was passed in and generically instantiating it with a dynamic constructor list.

The level keeps track of recursion to avoid infinite loops. You can tweak this as needed but I’ve seldom seen well-written systems go more than a few levels deep (for example, a controller may depend on a service that depends on other services). The dynamic nature of JavaScript makes it easier for us to build a component on the fly. First, we create an empty template:

Template = function () {}

Next, we get the component itself (which is a function, but it might be a constructor function, a factory, or a self-invoking function):

fn = annotatedArray[annotatedArray.length - 1],

Then we grab the annotations for the component. Remember, the last element of the array is the component itself. If the array has more than one element, we assume the previous elements are annotations. Otherwise, we check the component itself for the $$deps property, and failing that we assume it has no dependencies.

deps = annotatedArray.length === 1 ? (annotatedArray[0].$$deps || []) :
    annotatedArray.slice(0, annotatedArray.length - 1),

Now for the magic, we copy the prototype of the supplied component to the prototype of our template:

Template.prototype = fn.prototype;

Then we create an instance of the template:

instance = new Template();

Finally, we call a recursive invoke function to push in dependencies. If there are none, we use the instance we created, otherwise we use the fully wired result from the recursive call.

injected = _this.invoke(fn, deps, instance, lvl + 1);
result = injected || instance;

The recursive call simply checks the recursion level to make sure we haven’t gone too far, then iterates through the dependencies. Each dependency is pushed into an arguments list (as an instance that is also recursively retrieved from the container itself). We use the function to apply to the template we created with the arguments we’ve pushed.

for (; i < deps.length; i += 1) {
    args.push(this.get(deps[i], lvl + 1));
}
return fn.apply(instance, args);

Voila! Now we are able to retrieve a component with its dependencies. Here is an example of wiring up multiple components, some of them by annotating during registration and others annotated using the $$deps:

function main () {
    var ioc = new $$jsInject();
    ioc.register('courseMap', [CourseMap]);
    ioc.register('instructors', ['log', 'ch', Instructors]);    
    ioc.register('courses', ['log', 'ch', Courses]);
    ioc.register('log', [Log]);
    ioc.register('ch', [CollectionHelper]);
    ioc.get('log').log(ioc.get('courseMap').getCourses());         
}

You can see a full working example with this fiddle. Be sure to open your console log, that is where you can verify the call to the course map returns an expanded instructor and course but all dependent components are only created once even though they were registered in a different order.

Improvements

You can certainly improve the implementation (and I do accept pull requests). As an exercise, for example, how would you modify it so you could store constant values and not just instances of objects? In other words, what if I want to register the text “Copyright 2014” in a value called “Copyright”? Also, the current implementation for registration doesn’t implement chaining. Instead of ioc.register(x); ioc.register(y) it would be far more convenient to chain like this: ioc.register(x).register(y) … do you know how to fix it so that’s possible? What about a modification that allows you to determine whether you get the singleton, cached instance vs. force a “fresh” instance when you request it? (Hint: take a look at my Portable IOC project that supports this in C#).

Wrapping Up

As you can see, dependency injection itself is fairly straightforward and is designed to simplify your solution, not overly complicate it. Angular adds some extra caveats and shortcuts to their solution but in essence it behaves very similar to the example I’ve provided here. In fact, I hope by walking through this you can now go back to the Angular source and better understand what is happening in the $inject implementation. If you are able to use the jsInject component in your projects that’s an added bonus, but otherwise I hope you walk away feeling much better about using dependency injection and specifically how it can be implemented in JavaScript.

* Chimera image credit goes to AKHSMythology under the Creative Commons Attribution Share-Alike 3.0 License
* Hero image credit Office ClipArt

Thursday, June 26, 2014

WebSockets in Windows Store Apps

The WebSockets protocol provides full-duplex communication on top of a TCP connection that is initiated by an HTTP handshake. The fact that it runs over existing HTTP and HTTPS ports allows it to pass easily through most existing firewall configurations. The Windows Runtime provides a powerful set of networking APIs that includes components specifically designed for WebSockets communications. In this article, Jeremy Likness shows how to connect to WebSockets using both message-based and real-time connections from Windows Store apps.

Read the full article at InformIT.com.

Thursday, June 19, 2014

Programming the Windows Runtime (WinRT) by Example

In 2011 I heard the first rumors about Windows 8 and knew immediately what my next book would be about. Unlike Designing Silverlight Business Applications that captured years of experience writing Line of Business (LOB) apps in Silverlight, this book would be an introduction to an entirely new platform. My goal was to take what I knew and loved about Silverlight, find its similarities in the new platform, and then highlight what I felt were some amazing developer experiences. It was important to get to market fast, so through several iterations of the Windows 8 releases (including changes to terminology) that required substantial rewrites of content and a rapid release cycle, I managed to release Building Windows 8 Apps with C# and XAML as Windows 8 was released to the world.

showcover_half By necessity, this book introduced developers to the new platform but didn’t dig into best practices (there were none yet) or get very deep (there simply wasn’t time). I vowed to release another book that would fill in the missing pieces and provide a comprehensive overview of the entire Windows Runtime. Because anyone can read the documentation and reference the API, my intent with this book was to make it example-driven and provide thousands of lines of code for you to integrate and use to kick-start your own Windows Store apps. The result, according to Principal Program Manager Lead for the XAML Platform at Microsoft Corporation Tim Heuer, is that:

This book doesn’t just focus on singular concepts, it also provides end-to-end perspective on building an app in WinRT. It is one of those essential tools for Windows developers that will help you complete your software goals sooner than without it!”

I was relieved at the thought of not rewriting most of the book three times, as I had to do with the first one, but Microsoft once again proved too fast for me. What sounded at first like a relatively minor release (Windows 8.1) managed to integrate enough changes to warrant revisiting every one of the ten chapters I had completed to date. With an eye on //BUILD in 2014, I reached out to Windows Store expert and Wintellect colleague John Garland to help me finish the remaining chapters. John and I have worked on several projects together (and incidentally two of them won awards for their groundbreaking use of XAML for touch and mobile), and he helped write pilot code for several of our customers who were early Windows 8 adopters, so I knew he was the right person to bring a fresh set of example projects and content-rich chapters. As a bonus, he is also well-versed in cloud technology and brought this firsthand knowledge to bear in the chapters that deal with connecting to Azure.

With Windows 8.1 and the Windows Runtime, Microsoft has successfully demonstrated their commitment to the development ecosystem by providing us with a rich, vast array of APIs, SDKs, and tools for building incredible apps that run on a variety of devices. I was absolutely amazed when I discovered how easy it was to connect to a web cam, open a web socket, download files in the background, or profile my app to find “hot spots” that I could target to improve performance using WinRT. I was delighted to find that Portable Class Libraries (PCL), something I evangelized heavy as a solution to target multiple platforms in the Silverlight and WPF days, was evolving to embrace Windows Store apps. The first class support for mature design patterns like MVVM makes it easier than ever to write stable, reusable code that runs on a variety of target devices.

Programming the Windows Runtime by Example is a must-have book for any professional developer building apps for WinRT/Win8.1, especially the LOB space for modern apps on Windows 8.1. For me it is the reference I provide my team building LOB applications for WinRT. Jeremy and John have done a great job putting together a great reference and educational book on professional development for the WinRT platform.” – David J. Kelley, CTO and Microsoft MVP

In Building Windows 8 Apps with C# and XAML, I shared my intent to guide you through the process of learning the new territory quickly to begin building amazing new applications using skills you already have with C# and XAML. In this book, it is our goal to take you beyond that initial exposure and help you dive deep into all the various APIs WinRT makes available. Our goal was to hit virtually any scenario possible using the Windows Runtime—not just provide code snippets, but full projects you can use to experiment, learn, and use as a starting point for your own apps. The most rewarding feedback I received from my first book was hearing from authors sharing with me their excitement having their first Windows 8 apps approved for the Store. I hope this book not only helps take those apps to the next level, nor simply inspires your imagination, but empowers you to implement solutions you only dreamed possible using this incredible new platform. I know I speak for both John and myself when I say we look forward to hearing back from you about what you were able to achieve with Visual Studio, Windows 8.1, and this reference on your desk.

Don’t take my word for it – download the sample chapter (PDF) and read the full forward and table of contents along with a chapter about networking. Visit the code website to download the full source code. Finally, when you are ready, invest in your copy and let us know what you think!