Tuesday, July 28, 2009

Introducing Hiro, the World's Fastest IOC Container, Part III: The Container Itself

Introduction


In this final installment of the Hiro series, I'll show you just how ridiculously simple it is to use Hiro in your own applications without sacrificing speed for simplicity. I'll also show you how you can use Hiro's registration conventions so that you will never have to worry about managing any external configuration files or declare any external attributes on your types just so you can get your types registered into a service container.

Simply Fast, and Simply Simple


As I mentioned in my previous posts, Hiro lacks many of the "fat" features that you would normally associate with other IOC containers (including LinFu). At first, that might seem like a disadvantage for potential Hiro users, but it also implies that you won't have to waste any time trying to understand any IOC container features that you probably will never use in most of your applications. Instead, Hiro focuses on doing three things:
  1. Determine the list of available services from any given assembly.
  2. Registering those services into a container
  3. Ensuring that the container can create the services that you registered.
Unlike other IOC containers, Hiro doesn't need you to use fluent interfaces or attributes to register your types into a container. You don't even need lambda functions or an external XML configuration file to get your services up and running with Hiro. Instead, Hiro uses Convention over Configuration semantics that let you register your services with only a few lines of code. Here's an example:


// Use the loader to scan the target assembly
// for services
var loader = new DependencyMapLoader();

// The loader will handle all the details of loading
// the services into the container for you
DependencyMap map = loader.LoadFromBaseDirectory("SampleDomain.dll");
var container = map.CreateContainer();

// (Do something useful with the container here)
var greeter = container.GetInstance<IGreeter>();

// ...

"Convention over...what?"


At first glance, it's hard to believe that Hiro can load all the services from a given assembly (or a set of assemblies) using only the code that was given in the previous example. After all, any given service can have nearly an infinite amount of constructor and property injection dependencies, and given the sheer complexity of this task, there must be a set of rules that Hiro follows that somehow makes the registration happen "automagically". At the same time, there might be some end-user developers out there that might want to have strict control over the actual services that will be registered into the compiled container. In other words, how does Hiro know exactly what to register and still be able let users control what gets registered into a compiled container?

A Few Rules Go A Long Way


Now the reason why Hiro can do so much in so few lines of code is because that it implements a few conventions that typical IOC container users would follow when registering their own types. As long as users follow those conventions, they will never have to worry about manually registering any of their service types with Hiro. For example, let's assume that you had this particular service type declared in a single assembly:

  
public interface IGreeter
{
void Greet(string name);
}


Let's also assume that you have three concrete classes that implement the same IGreeter interface:
  
public class GermanGreeter : IGreeter
{
public void Greet(string name)
{
Console.WriteLine("German: Hallo, {0}!!");
}
}

public class FrenchGreeter : IGreeter
{
public void Greet(string name)
{
Console.WriteLine("French: Bonjour, {0}!", name);
}
}

public class Greeter : IGreeter
{
public void Greet(string name)
{
Console.WriteLine("English: Hello, {0}!", name);
}
}



"Just give me the default service, please!"


Based on the examples above, it probably didn't take you very long to infer that the Greeter class is the default implementation for the IGreeter interface. Furthermore, it's probably safe to assume that a default implementation exists if you have an interface named IYourService and if you already have a concrete class named YourService that implements that particular service type. Hiro follows the same convention, so calling container.GetInstance on an IGreeter type will yield a Greeter instance:

  

// Load the sample assembly
var loader = new DependencyMapLoader();
DependencyMap map = loader.LoadFromBaseDirectory("SampleDomain.dll");
var container = map.CreateContainer();

// Get the default implementation
var greeter = container.GetInstance<IGreeter>();

// Determine the actual type that implements the IGreeter interface
var greeterType = greeter.GetType();

// This expression will return true
Console.WriteLine(greeterType == typeof(Greeter));


As you can see, the example above is fairly self-explanatory. The DependencyMapLoader class will automatically determine that the Greeter type is the default implementation for the IGreeter interface and register it into the DependencyMap. Of course, this approach assumes that you have a class with a type name that matches the service type name; however, there might be cases where you have multiple classes that implement the same interface but don't follow this naming convention. For example, if I have the FrenchGreeter and a GermanGreeter class but don't have a default Greeter class, how does Hiro determine which implementation should be used as the default implementation type?


When All Else Fails, Use the Alphabet


The answer is that by default, Hiro will pick the first implementation type from a list of service implementations that have been sorted alphabetically by type name. In this case, Hiro will choose the FrenchGreeter as the default IGreeter implementation since the FrenchGreeter class name alphabetically appears before the GermanGreeter class name:


// ...

// Get the default implementation
var greeter = container.GetInstance<IGreeter>();

// Determine the actual type that implements the IGreeter interface
var greeterType = greeter.GetType();

// This expression will return true since
// the FrenchGreeter type appears before the GermanGreeter type
Console.WriteLine(greeterType == typeof(FrenchGreeter));


While this approach might be useful for determining (and thus accessing) a default service implementation, there has to be a way to access the other concrete IGreeter implementations that reside in the compiled container. As it turns out, Hiro makes this process just as equally effortless:


// Get the French and German greeters
var frenchGreeter = container.GetInstance<IGreeter>("FrenchGreeter");
var germanGreeter = container.GetInstance<IGreeter>("GermanGreeter");


By default, Hiro registers each service implementation using the class name of each concrete service type. In order to access a particular service implementation, all you need to do is pass the name of the implementing type in the container.GetInstance<T> call, and the container will instantiate the corresponding type for you.

Using Constructor Injection and Property Injection


Now that we have an idea of how Hiro registers service types into a container, the next thing that you might be wondering about is exactly how Hiro injects dependencies into constructors and properties. For example, if I have a class named GreeterHost that takes one IGreeter dependency in its constructor, how do I tell Hiro to use that constructor instead of the default constructor? Let's take a look at the GreeterHost class:


public class GreeterHost
{
public GreeterHost ()
{
}
public GreeterHost(IGreeter greeter)
{
// Do something useful here
}

// ...
}


Let's also assume that I manually registered the GreeterHost class with the DependencyMap using the DependencyMap.AddService method. Here's how you get Hiro to perform constructor injection:



// Manually add the GreeterHost to the dependency map
var map = new DependencyMap();
map.AddService<GreeterHost, GreeterHost>();

// Manually add an IGreeter service so that Hiro uses the constructor
// with the IGreeter parameter
map.AddService<IGreeter, Greeter>();

// Compile the container
var container = map.CreateContainer();

// Create the GreeterHost. Hiro will automatically
// inject the IGreeter implementation into the constructor
var greeterHost = container.GetInstance<GreeterHost>();


As you can see from the example above, Hiro automatically used the contents of the dependency map to determine which constructor should be used for instantiating the GreeterHost type. The only thing that I needed to do to perform constructor injection was to make sure that the IGreeter service type was available in the dependency map once the container was compiled. The compiled container, in turn, used the IGreeter dependency to call the correct GreeterHost constructor.

Singletons Galore


NOTE: If you prefer to have your Greeter type registered as a singleton in the dependency map, however, here's how you do it:


// Manually add an IGreeter service so that Hiro uses the constructor
// with the IGreeter parameter
map.AddSingletonService<IGreeter, Greeter>();


Constructor, Inject Thyself


The best part about the constructor injection example with Hiro is the fact that it handles all the gory details of performing constructor injection for you in the most minimal lines of code possible. In this case, the only convention that you have to follow is to make sure that the dependency map contains all the necessary services for Hiro to call the appropriate constructor. What makes this even more interesting is that Hiro can perform automatic constructor injection with constructors that have any arbitrary number of constructor arguments. In other words, if the DependencyMap instance has the constructor dependency, then Hiro can handle the injection.


Property, Inject Thyself Too


For the most part, Hiro's property injection follows some of the same conventions as constructor injection. Much like constructor injection, the only thing you need to do to use property injection with Hiro is to make sure that services required by the target property are already registered with the dependency map once the container is compiled. For example, let's assume that GreeterHost class as an IGreeterProperty named CurrentGreeter:


public class GreeterHost
{
public IGreeter CurrentGreeter
{
get;set;
}
}


Here's how you set up Hiro's dependency map to perform property injection:


// Manually add the GreeterHost to the dependency map
var map = new DependencyMap();
map.AddService<GreeterHost, GreeterHost>();

// Manually add an IGreeter service so that Hiro uses the constructor
// with the IGreeter parameter
map.AddService<IGreeter, Greeter>();


The first thing that you might notice is that the setup code for property injection and constructor injection are both identical to each other. In fact, you could even say that I just "copy & pasted" the example from previous examples in this article. Indeed, that was intentional, and the point here is that are only two simple things that you need to do to make Hiro automatically perform property injection on your types:

  1. Ensure that the service types that your properties require are registered with the dependency map.
  2. Ensure that the properties that will be injected are not read-only properties.
In other words, Hiro's property injection conventions follow one of the most basic dependency injection conventions of all:

If you don't want Hiro to inject dependencies into your target property, then make sure the property is a read-only property or the property type doesn't exist in the container as a service type.


All you need to do to disable property injection for the GreeterHost is to prevent a default IGreeter service from ever being registered into the dependency map. You can do this by either constructing the dependency map by hand, or you can attach a service filter to the DependencyMapLoader so that it avoids loading a default IGreeter service into the resulting dependency map:


var loader = new DependencyMapLoader();

// Make sure that no default service is loaded for the IGreeter interface
loader.ServiceFilter = service=>service.ServiceType != typeof(IGreeter) && string.IsNullOrEmpty(service.ServiceName);


As you can see from the example above, all you need to do to prevent the DependencyMapLoader from registering services is use a simple lambda function, and it can't get any simpler than that.

Next, here's the call that will construct the GreeterHost and perform the property injection operation if you still have the required dependency inside the container:


// This is the only method call you need
// to do property injection
var greeterHost = container.GetInstance<GreeterHost>();

// ...


Fortunately for the end-user developer, the GetInstance method that performs the constructor injection is also the same method that will perform all property injection operations. Hiro uses these simple conventions to make developers' lives easier, and if it can help at least one person out there write better code, then I consider this project to be a success.

--

You can download Hiro from here.
You can also click here to download the Hiro example solution.

Friday, July 17, 2009

NDepend Review

The Quick & Dirty

There have been a lot of good reviews written for NDepend, so for the sake of efficiency, I'll get straight to the point: NDepend is an amazing tool. It lets you graphically inspect your assemblies and it lets you pinpoint the spots in your code base that need refactoring.

So would I recommend buying NDepend Professional? Yes.

Is there something that I didn't like about NDepend that I think the users should know about? Yes, and that's exactly what I'll talk about.

"So what's not to like about NDepend?"

My only problem with NDepend is that its CQL query engine can only be accessed from the Visual NDepend application. NDepend does let you embed CQL attributes in your applications, but the problem is that I shouldn't have to force each one of my applications to have a dependency on NDepend just because I want to have some code metrics calculations in my build process. Of course, there are a few ways that I can work around that limitation, but the point is that I shouldn't have to make a workaround for something that should have been there in the first place.

In other words, what NDepend sorely needs right now is a publicly-accessible CQL engine API. If NDepend is truly a tool built by developers for developers, then it should have an API that other developers can use to analyze their applications. It's not enough to throw them a rudimentary command-line tool that spits out code metrics in XML--that pretty much leaves developers to write code against the "shadow" of the CQL API rather than write against the CQL API itself, and for me, that just doesn't quite cut it.

Don't get me wrong--the Visual NDepend winforms application is an awesome app--but I'd rather be able to filter through all that information using a single API call rather than have to manually sift through several windows just to find the information I need.

Now the reason why I'm harping so much about the lack of a public CQL API is that my company uses NDepend Professional in its command line builds to ensure that our builds fail when the Cyclomatic Complexity score exceeds 2.5 in any of our projects. The problem is that we want our code quality inspections to be completely automated, and we can't do that unless we have access to the CQL API and can generate CQL queries at runtime. The maximum Cyclomatic Complexity score might prevent our developers from writing complicated code, but there's far more to code inspections than just looking at a single score. What we need is a way to look deeper into the quality of our code base using the hypothetical CQL API with the same ease that Visual NDepend users can browse through their code.

So in the end, I still recommend NDepend Pro as definite buy, but it still lacks a few key features that would make me give Patrick Smacchia's tool the gushing review that other bloggers have given it in their respective reviews. Overall, it's definitely a great tool, but it's not without a few shortcomings.

[Public Disclosure: Thanks to Patrick Smacchia for providing me with a free NDepend Pro license for this review.]

Ratings by outbrain