Discord&Rhyme Joins The Lounge

Twitter is fantastic, because you can use it to meet some really interesting people. One such person I ran into in the Twitterverse is James Avery, who runs The Lounge, an internet ad network focused on technology. When he invited me to join the .NET Small Publishers Room, I was flattered, because I had already subscribed to several of the blogs that were featured there. It’s an honor to be featured alongside such auspicious company.

For those that read my blog from the site itself, you’ll notice a small ad in the top right corner. For those that read the RSS feed, you won’t notice any changes.

Bait-and-Switch and Software Licenses

Jack Slocum and the rest of the Ext JS team recently released version 2.1 of their fantastic toolkit. If you’re not familiar with Ext, it’s a user interface library that lets you write rich Internet applications (RIAs) using JavaScript. It’s more than jQuery or Prototype, in that it gives you full-fledged components like dialogs, grids, and trees in addition to the typical animation and language-enhancement features of the other JS libraries. If you develop RIAs and you haven’t tried Ext, I highly recommend you check it out.

That being said, the Ext team slipped in a little surprise with their latest release. Up until version 2.1, Ext was released under a dual-license model, with one option being an LGPL-compatible license and the other a commercial license. From this point forward, they’ve changed the options to GPL (as in, full copyleft) or a commercial license. This means that in order to upgrade to the latest version, all products which had previously relied on Ext will now have to start distributing the source — of not only Ext, but also their own products — in order to remain within license.

As you might imagine, this caused quite a stir within Ext’s already-quite-large user base. First, let me say that I am absolutely a believer in open-source software. Open-source means you can use the code in your own projects, commercial or otherwise. You can read the code and learn from it. You can contribute patches and ideas, furthering the project’s development. However, there is a tremendous difference between what I would call open-source licenses (Apache, BSD, MIT, et al.) and copyleft licenses like the GPL.

(Note: some people will disagree and say that GPL is still open-source, but I’m not trying to debate semantics. This post will refer to the two types of licenses separately.)

Ninject, for example, is open-source (Apache 2.0, actually), and I fully encourage anyone and everyone to use it in as many commercial products as they like. If you make a billion dollars through a product that uses Ninject, I’d appreciate it if you bought me a beer, or maybe my own private jet on 24-hour standby, but otherwise I would be nothing but happy for you. :)

The GPL is fine for things like operating systems and applications, which are essentially standalone. These products aren’t going to be re-used in other products. However, libraries, frameworks, and any sort of middleware should never, ever, ever be released under a copyleft license like the GPL. Copyleft is viral, in that the second it touches any part of your code, you must open its source. Ostensibly, that is perfectly reasonable, but the difference between closed-source and open-source is a business decision, and a very significant one. Your business model determines whether you can or should run your project as open- or closed-source.

Ask yourself: are you really going to build your business model around the license of a library like Ext? My guess is that most people would just find another way, and that discourages adoption of the library. It’s true that if people are making money off of Ext, it’s reasonable they pay the creators, but changing the license of the library after there are a lot of products that already use it is downright unfair. The Ext team is playing dirty, and people have every right to be upset.

There’s nothing wrong with wanting to be compensated for your work, particularly when you create something as widely useful as Ext. However, waiting until version 2.1 to change the license model for your software (not to mention changing it on a point release rather than a full dot-oh) strikes me as a little bit dishonest. Unless we give them the benefit of the doubt, it sure seems like they leveraged the openness of LGPL to get control of market share and build their user base, and then pulled a major bait-and-switch once they locked users in.

Bear in mind, also, that Ext was originally called yui-ext, and was built on top of YUI, the Yahoo! UI Library, a BSD-licensed toolkit. Basically, the Ext team stood on the shoulders of open-source, putting on airs as though they were participating, and then when the time was right they slammed the door shut.

Worse yet, the Ext community has contributed back a large number customized components and enhancements to the library. The Ext team hasn’t explicitly rolled these enhancements into the core, but they have undoubtedly learned from them and enhanced the code library as a result. I’ve also seen several cases where people submit code change suggestions (essentially patches) on the forum, which end up being rolled into the core. It’s not fair to have it both ways — accepting outside ideas means you have a responsibility not to screw the people that contribute those ideas.

At best, this is a terrible blunder on the part of the Ext team, and at worst, it’s a blatant misuse of open-source licenses. This is not what the GPL and the LGPL were created for. Also, it’s cases like this that add to the FUD surrounding open-source. After seeing things like this, I don’t blame businesses being afraid of adopting open-source in their products, for fear of the rug being pulled out from under them. And that’s not fair to real open-source libraries.

Of course, all this nonsense begs the question: how do you GPL a web application, anyway? In a typical website based on Ext, there’s client-side code written in JavaScript, which uses Ext for the user interface, and then there’s server-side code written in any of a myriad of languages which doesn’t come near Ext. Does using Ext on the front-end mean you have to open-source your entire product?

There’s all sorts of gray area there, which Jack desperately tries to explain. His reasoning? If your server-side code generates markup, then yes, you need to open-source it. What if the JSON/XML that I send back to the UI influences the layout? Do I need to open that source also? Now I need to employ a whole legal team to try to decipher whether or not I’m GPL-compliant.

Jack tries to defend the decision thusly:

In the end, we want Ext JS to be open source friendly and still have a good business model in place to grow. The old Ext License was not open source friendly and pretty much killed all options for use in open source projects. That wasn’t our goal so we had to address it.

To be perfectly blunt, that’s a crock of shit. The only reason the old Ext License wasn’t open-source friendly is because it wasn’t really the LGPL and therefore not OSI-approved. Why didn’t they use the LGPL, you ask? They were worried that someone would fork the project. Tell me again that they weren’t planning this all along.

Oh, and by the way, they’re not opening up the project’s Subversion repository. You can download official releases, but you can’t have direct access to the latest builds — unless you buy a commercial license. That’s technically fair, but doesn’t exactly jive with the concept of open-source.

On one hand, I feel for Jack, who has been a target of personal attacks because of this license change. He attempts to defend himself on his blog. However, it’s easy to see why people are upset, and I can’t believe he didn’t see it coming. I understand that you need to protect your intellectual property, but you need to recognize that open-source is a give-and-take (quid pro quo, as the Ext site says) — you give users free access to the library, and in exchange you get community support and good ideas. Changing from LGPL to GPL doesn’t protect the library from being misused by “major companies”, either. Sorry Jack, but they’re still banking on the fact that you don’t have the money to sue them.

To be fair, it does look like they’re considering a FLOSS exception like MySQL has, so non-copyleft open-source projects can continue to use the library. Why even change, then? You’re going to end up with essentially the same outcome as a result.

Using the GPL in this way arguably causes a chilling effect not unlike closing the source completely. By requiring users to release their source, you are shutting out a potential segment of users. It’s very easy to see that if Ext had been licensed under the GPL since inception, it would not have nearly the mind-share it does today.

Since I use Ext in my “day job” in for-profit products, we were happy to buy a commercial license. However, now that it’s licensed under the GPL, its much more difficult for me to consider using it in side work or hobby projects.

Great IoC Presentation by Justin Etheredge

Justin Etheredge gave a great presentation on dependency injection and inversion of control last week at the Richmond Code Camp. It gives a very good introduction to DI, which is something that I’m going to try to tackle at the Cleveland Day of .NET in a few weeks. Plus, he uses Ninject in the examples and was kind enough to quote me in the presentation, so it’s got to be good, right? :)

Seriously, though, if you weren’t able to see the presentation, Justin’s posted the slides and related code samples on his blog. I highly recommend you check them out if you’re interested in learning more about dependency injection!

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!

Ninject Release Candidate 1

I’ve been busy the past few evenings adding some features to Ninject to move it towards the impending 1.0 release. I’ve written about a few of them before, but here’s a quick breakdown of the changes.

Transient Parameters

Previously mentioned here and here, transient parameters provide a means to manipulate the activation process for active requests to the kernel’s Get() method. Since I previously wrote about them, I’ve rewritten the internals to generalize them. Now, you create custom parameters using the IParameter interface, and extensions or your bindings can read them and alter the activation process.

Aspect-Oriented Programming (Interceptors)

I briefly talked about this before also. Since dependency injection frameworks like Ninject already control object instantiation, it’s natural to add the ability to intercept method calls on the generated instances. I’d flirted with adding support in the past, but I was wary of spending the effort to write a large proxy-generation system. I was also concerned about bloating the core library, since not everyone will use interception.

Finally, I settled on "outsourcing" the hard part — proxy generation — to already-existing libraries like LinFu.DynamicProxy and Castle DynamicProxy2. The actual interception system is baked into Ninject.Core, but in order to actually use it you have to use one of these libraries and the corresponding integration extension. (You can also create your own integration, of course!)

There are two ways to define interceptors in Ninject: static and dynamic. Static interceptors are related to a single method, and are declared via attributes. The main attribute is InterceptAttribute, which can be used directly or extended to clean up the code. You can tag either a single method with an interception attribute, in which case only that method will be intercepted — or you can put the tag on the class itself, which will cause all methods on the type to be intercepted.

With Ninject’s history of fancy fluent interfaces, though, that’s way too boring. Naturally, I had to up the ante a bit, with what I call dynamic interceptors. These are defined kind of like bindings, in a module’s Load() method. If you’ve used the conditional binding system, you’re familiar with fluent interface rooted in the When class, that can be used to create binding conditions. Well, my super-secret plan has now been un-veiled; the same fluent interface can also be used to define dynamic interceptors.

There’s now a new method, like Bind(), available in modules, called Intercept(). This means that if you want to define dynamic interceptors, you can do things like this:


Intercept<CacheInterceptor>(When.Request.Method.ReturnType.EqualTo(typeof(int)));
Intercept<CountInterceptor>(When.Request.Method.Name.StartsWith("F"));

As you might guess, the first registration will cause all method calls to any objects activated via the kernel to be intercepted by a CacheInterceptor. The second registration causes all methods starting with the letter "F" to be passed through a CountInterceptor. Naturally, these are contrived examples, but you can see the power available to you.

One more cool feature ties together the two fluent interfaces in a very interesting (at least to me!) way. If you do:


When.Request.Context

You can actually write conditions against the activation context (IContext) that the object that is being intercepted was activated in! (Whew. That’s a mouthful.) This means you can make interception decisions based on a type’s activation plan, or even transient parameters passed to the Get() method.

NOTE! This also means there’s a breaking change in the conditional binding system. Anywhere you were using When, you will now have to replace with When.Context. Sorry, I’ve been trying very hard to avoid breaking changes, but this one was necessary.

The new AOP support in Ninject deserves its own blog post (or series of blog posts). It’s one of my favorite new features, and I’ll continue to write about it as time goes on.

New Tracking Component and Scopes

I’ve refactored instance tracking, used for deterministic disposal, out of the kernel itself and into a new ITracker kernel component. I’ve also introduced a new scope system, which you can use for more fine-grained control over deterministic disposal:


IKernel kernel = ...
using (kernel.BeginScope())
{
  IService service = kernel.Get<IService>();
}

The BeginScope() method returns an IScope object, which is disposable. As long as a scope is active, any instances that are created are registered in it. When the IScope is disposed, all instances that were created therein are passed to the kernel’s Release() method.

Extension Model

One of the driving forces of Ninject has been to keep the core library as slim as possible. This has resulted in a lot of additional assemblies, and until this point there hasn’t been a natural way to load them into the kernel. The new extension model uses the concept of Ninject modules as a plug-in architecture. For example, the pub/sub messaging system, which used to live in Ninject.Messaging, is now in Ninject.Extensions.MessageBroker. To use it, all you have to do is add the MessageBrokerModule to your kernel:


IKernel kernel = new StandardKernel(new MessageBrokerModule(), ...);

As more extensions are created, they will typically exposure an IModule that can be loaded into a kernel to extend it with the functionality provided by the extension.

Cleanup and Minor Enhancements

I’m starting to revamp parts of the code to take advantage of the syntax improvements available in C# 3.0 — particularly lambda methods rather than anonymous delegates. I’ve also spent some time moving some things around in the solution to get it more organized, including tinkering with namespaces to limit the types that are exposed to code that consumes Ninject and its extensions. I’ve also provided a strong-name key and signed all of the assemblies to allow them to be used in scenarios that require it.

I’m sure there’s a bunch of other things that I’ve added, but those are the ones that I can remember at the moment. If you’d like to tinker with Ninject, there’s a new build available on the project website, or you can check out the latest version from the trunk and build it yourself. I’d like to hear what everyone has to say about the new features. I’m targeting June for a final 1.0 release, and I’d like to know what you think is missing before we can call it the big one-oh.