Entries
RSS 2.0

Comments
RSS 2.0

Come Hear Me Ramble

I will be speaking at the Cleveland Day of .NET on May 17th. If you’ve heard of this inversion of control and/or dependency injection stuff and would like to hear more, by all means come on up to sunny Cleveland! Here’s the abstract for my talk:

The old adage states that the only thing that remains constant is change, and nowhere is this more true than in software development. In this presentation, Nate Kohari describes how to apply the principles of inversion of control and dependency injection to create software that can adapt to changing requirements. Learn to break your monolithic app into loosely-coupled, highly-cohesive pieces… then glue them back together with an inversion of control container to create ultra-flexible code that you can bend to your will.

If you’ve never used dependency injection, this talk should prove to be a good introduction, and I’ll be happy to answer any and all questions. Or, if you’re already experienced with dependency injection, come see how Ninject can free you from the pain of XML!

Also, I’m still relatively new to public speaking, so there’s always the chance that I’ll completely choke and you can throw tomatoes. What’s more fun than that?

Announcing Ninject Contrib!

A few days ago, I accepted the first patch for Ninject, an NLog integration extension by Ivan Porto Carrero. Ivan subsequently created a couple other extensions for Ninject, and rather than put them directly into the main project, we decided to launch Ninject Contrib to collect contributions from the community.

If you’ve got any ideas for Ninject extensions, or if you come up with any examples that you’d like to share with the rest of Ninject users, feel free to post your idea in the Ninject developers group and I’ll set you up with commit access.

Major thanks to Ivan for his contributions, and his excellent ongoing series of Ninject-related articles!

This Is Why We Can’t Have Nice Things, People

Rob Conery (a Microsoft employee) has been working on a series of screencasts (part one, part two) illustrating the construction of a web commerce application using TDD. His intent is to learn the process, and by doing so, help others to do the same. These screencasts have caused some major backlash on the intertubes, where people have attacked him for not fully understanding TDD, and therefore presenting his allegedly poor ideas as Microsoft best-practices. The debate culminated in a conference call between Rob, Aaron Jensen, Ben Scheirman, and Scott Bellware.

First off, let me say that Microsoft must have killed Scott Bellware’s puppy or something. All you have to do is say the word “Microsoft” to raise his blood pressure to unhealthy levels. He’s clearly very intelligent, and has good things to say, but every time he tries to make a point, it gets drowned in piss and vinegar.

Note to Scott: not everything has to be Israel vs. Palestine. We want to hear what you have to say, but lay off the holier-than-thou stuff and you won’t come off sounding like a pompous ass. People don’t respect those that don’t respect others. The more you alienate people, the less you’ll be taken seriously — and the less effective you will be at getting your message across.

Anyhow, a comment by David Nelson on Rob’s post describing the conference call sums up why this whole situation is ridiculous:

When you open up with “My name is Rob Conery and I work for Microsoft”, you are declaring yourself to be an expert at whatever you are talking about.

Are you kidding me? I really hope that this is an aberration and the majority of the .NET community doesn’t feel this way. If someone works for Microsoft, I tend to think they have their finger on the pulse of what’s going on in the company (or at least in DevDiv) — but Microsoft is a huge corporation, so even that is suspect. Just because someone works for Microsoft doesn’t mean they’re an expert at anything, or should even be listened to in the first place. Now, I tend to think Rob is a pretty sharp guy, but that’s more due to his contributions to the community than the fact that he works for Microsoft.

Software developers are smart people. Since when did we forget how to think for ourselves?

This, in a nutshell, is what’s wrong with the .NET community, and why Microsoft largely remains a “walled garden”. If a Microsoft employee can’t communicate their perspective to the community at large without it being taken as the One True Way, they will simply stop talking, and the trumpet of Sales and Marketing will drown out the voice of the technologists. This is not the fault of Microsoft employees, or the company itself. If people truly do take the word of Microsoft employees as fact, the problem is systemic, and each developer that thinks this way shares in the blame.

This is also at least part of the reason why Microsoft has traditionally been hesitant to associate their name with open-source software. This results in an offshoot of the Not Invented Here syndrome, Not Invented at Microsoft — which leads to unnecessary projects like MSTest, ASP.NET MVC, and Unity. Don’t get me wrong, there’s nothing inherently wrong with Microsoft creating these projects, but they are all “me-toos” created after similar open-source efforts (NUnit, MonoRail, and Windsor, respectively) have had success. Now, I understand that a lot of developers have difficulty convincing the “powers-that-be” in their companies that open-source is a viable alternative to commercial software. A lot of companies are wary that if they build their products on open-source, if they need commercial support, it won’t be there.

However, what if, instead of hiring leaders of the .NET community to create official, Microsoft Brand(tm) alternatives to existing open-source software, Microsoft certified and funded open-source projects directly? For example, NHibernate and the Castle Project are two of the most well-respected open-source efforts in the .NET community. Their software provides fantastic value to a huge number of companies.

What if Microsoft awarded these projects a grant, so they can provide commercial support, and then told its customers that these are quality software products, and are safe to use in their infrastructure? Microsoft would save money, improve the legitimacy of .NET as a development platform, and give the developers that donated their time to the community a chance to make their hobby into their day job.

As long as the average .NET developer believes that what someone says is solid gold just because their paycheck says Microsoft on it, this will never happen.

Extension Methods in .NET 2.0

One of my favorite new features of C# 3.0 are extension methods. However, for some projects I’m not willing or able to target version 3.5 of the .NET framework. Up until today I thought that this meant I was out of luck in terms of being able to use extension methods, until Scott Hanselman’s post about them got the gears turning in my head.

If you try to add an extension method in a project that targets version 2.0 of the .NET framework, you’ll get an error saying you have to reference System.Core. However, the error is misleading. Extension methods are just normal static methods tagged with the [Extension] attribute. This attribute is actually just added by the compiler behind the scenes. In .NET 3.5, it lives in System.Core, but if you define your own attribute like this:


namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
  public class ExtensionAttribute : Attribute
  {
  }
}

Your extension methods will suddenly spring to life! After testing, I realized I’m not the first one to figure this out, but it’s definitely something I’ll keep in my bag of tricks.

New Design for Ninject

I just launched the Ninject site redesign that I’ve been working on for the past week or so. I was a half-assed web designer in a former life, so I dredged up a bit of my graphic design skills. Major thanks goes to Ike Allred of Sibling Systems, who was nice enough to let me use his sweet ninja illustrations.

You’ll also notice that there’s a new bug tracker and wiki set up for Ninject. I’ll be working over the next few weeks to move documentation to the wiki so the community can contribute. If you find bugs, or have feature requests, feel free to enter them in the tracker.

Anyhow, check out the site and let me know what you think!

Frameworks and the Break-Even Point

I read a good post by Joel Ross the other day. In the post, Joel implements a simple project using Castle Windsor to drive dependency injection. In one of the comments, Matt Blodgett says that it seems like it takes a lot of code to implement, and that the code isn’t pretty. Naturally, I figured I’d use this an opportunity to point out the advantages of Ninject’s fluent interface vs. XML configuration. :)

The way I see it, every framework library has a cost that you have to pay up-front in order to use the library in your code. This cost might be in a learning curve, a performance penalty, or the fact that you have to write some boilerplate code to make the library work its magic. Typically, the argument is that by paying this up-front cost, you get a benefit that’s significantly larger. This creates a break-even point, where you make up for the “debt” you paid to use the library, and start becoming more effective because of it. The best libraries are the ones that keep the up-front cost as low as possible, so you reach your break-even point faster. Libraries that accomplish this goal can be used in significantly smaller projects, because it becomes easier to justify the up-front cost if you know that you’re going to quickly begin to see benefits in terms of efficiency.

Ninject was written to support enterprise applications, but aims to treat small projects as first-class citizens. To that end, I’ve gone to great pains to try to keep things simple in simple situations, and mask any complexity required for advanced scenarios from everyday use. Here’s the same example that Joel presented, written with Ninject.

First, the User class:


public class User {
  public IServiceApi Service { get; private set; }
  public string UserName { get; private set; }

  [Inject]
  public User(string userName, IServiceApi service) {
    UserName = userName;
    Service = service;
  }

  public void SendMessageTo(string message) {
    Service.SendMessage(String.Format("@{0} - {1}", UserName, message));
  }
}

One caveat: I typically try not to combine service logic with my domain model, and so I wouldn’t put the IServiceApi dependency directly in the User class. Not that there’s anything wrong with this, but it means that you have to activate every User that you load in your application via the DI framework, and that can interfere with scalability. It also makes activating the User a little bit more difficult, as you’ll see below.

Next, rather than creating the XML configuration to wire up the components, we create a module, and bind the IServiceApi interface to the TwitterApi implementation:


public class TwitterModule : StandardModule {
  public override void Load() {
    Bind<iserviceApi>().To<twitterApi>();
  }
}

(You could also add a self-binding for User, but you don’t have to since it’s a concrete type.) Maybe it’s just me, but those 4 lines of code (complete with IntelliSense!) are much simpler than the 20 or so lines of XML. You’re using a big powerful IDE, so why not take advantage of it to set up your DI framework?

Lastly, we need to load the module into a kernel and activate our User. Because of our userName parameter, we need to do a “hybrid” activation by passing a transient parameter to the Get() method. (This is what I meant about separating the domain model from the service model. It lets you avoid things like this.)


public static class Program {
  public static void Main() {
    IKernel kernel = new StandardKernel(new TwitterModule());
    User user = kernel.Get<user>(
      With.Parameters.ConstructorArgument("userName", "RossCode")
    );
    user.SendMessageTo("test");
  }
}

You could also just make the User’s UserName property writable, and set it after activating the object.

Now, this is a pretty simple example, and I’d say we still haven’t reached the break-even point with Ninject. However, if we had a couple more services like IServiceApi, each implementation of which had its own dependencies, the power of DI would start to make itself apparent. For example, consider the following scenario:

1. Our TwitterApi depends on a TwitterWebService.
2. We add a JabberApi which depends on a JabberClient.
3. We add a SmtpApi which depends on a SmtpClient, which depends on an EmailMessageFactory.

Assuming JabberClient, SmtpClient, and EmailMessageFactory are all concrete types, your existing application could support all of these new features without adding anything new to your type bindings. (This is because Ninject will automatically create “self-binding” when it encounters concrete dependencies.) You could then easily flip between the different options by altering the binding between IServiceApi and one of your *Api classes. Also, since your module is executable code like anything else, you could make it more intelligent, reading configuration files, command line parameters, or even a database to determine which messaging service implementation should be used.

The flexibility that inversion of control brings to your application benefits you the first time you need to add additional features, or make changes on the fly. Sometimes it’s difficult to understand what the benefit is by reading example code, and it takes some time to get used to writing your code to work with DI. It’s well worth the up-front cost though!