First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

February 2009 Blog Posts

The ALT.NET Conference: loving it

It’s been a great trip, and landed yesterday in Seattle with snow on the ground, but a wonderful sun. And this morning it’s still sunny (that’s the view from my hotel room).

mountain_range_from_hotel

Right now I’m the lounge at DigiPen, waiting for the second day of ALT.NET Conf to start.

The opening evening was very very interesting, and Phil Haack already wrote a great commentary of it.

I’m really impressed by the huge amount of smart people that are attending, and it’s also a great opportunity to meet people I’ve been interacting with only online. A funny thing is that we know each other by the name of the blog, but not by names. Yesterday it happened to me to introduce myself to people I know by twitter or by blogs and having this kind of conversation:

me: “Hi, I’m Simone Chiaretta, nice to finally meet you in person”.

other: “I don’t think I know you”.

me: “My blog is Codeclimber”.

other: “Oh… now I get who you are, nice to meet you in person”.

And yesterday it was finally the time all the “three Musketeers” of Subtext met in person.

IMGP3248

And in this pic I look way better (even if it’s hard to look good after being awake for 30hrs) than the pic on Phil’s post.

It will be a busy week, with the ALT.NET Conference in the weekend, MVP Summit the first three days of the week, and various events almost every evening. At least I’ll be arriving home back on Friday so I’ll have all next weekend to recover.

Ninject 2 hits beta status

logo

It’s not that a secret that I’m a big fan of Ninject, so I’m pretty excited to see that the experimental version that Nate was playing with has been “upgraded” to the next official release of Ninject, v2. It’s completely written from scratch, and it takes full advantage of LINQ.

You can read more about what’s new, what has been removed, and what has been added on the official announcement on Nate’s blog.

It seems like it also have an even easier way to integrate with ASP.NET MVC.

I’ll not have a lot of time to play around with it as my next week is going to be very busy, but I hope to find some time when I come back from Seattle.

Technorati Tags:

Fix the date: Italian ALT.NET Conference Summer Edition

We just booked the room, and fixed the date for the next Italian ALT.NET Conference: it will happen on Saturday June 27th, and will be held in Bologna (which is not where Spaghetti alla Bolognese was invented).

The event is co-hosted by UGIALT.NET, the Italian ALT.NET user group, and DotNetMarche, the .NET user group from Marche.

I’m really happy to be able to organize this event together with the DotNetMarche guys, which proposed this collaboration last year when I talked about ASP.NET MVC at one of their workshops. This workshop was supposed to be held on a beach on the Adriatic Sea, but later we decided to move to more central location: that’s the reason why we ended up in another region.

I already published a similar post on my Italian blog, but if someone from other countries want to come and attend to the event, he is more then welcome (knowledge of Italian will be plus).

Joining "IE6: Do NOT want!" campaign

UPDATE: It seems like Facebook joined the campaign as well: Facebook joins the war against IE6!!!

If you are accessing my blog with IE6 you will see above the header a green box that informs you that you are using a "obsolete" browser, and that there are more modern browsers available: IE7, IE8 beta, Firefox, Safari and Opera.

It all started with a tweet by Erlend Schei, developer for Finn (a kind of Norwegian eBay):

To everyone involved with major Norwegian websites: Why don’t we start a campaign to get rid of IE6? One week with visible upgrade suggestions on the frontpage.

The reason for his suggestion, which can be read on his blog is that "it would have been much better to use to make real good tool for users, rather than to correct errors that occur only in IE6"

And this got a huge response and in a few days the warning message was on all main sites in Norway. This campaign seems also to be kind of endorsed by Microsoft Norway. In a press release they say:

[...] The newer versions of Internet Explorer have support for international webstandards and significant improvements have been made to both security and functionality. Based on this we support the initiative that has been made to upgrade from Internet Explorer to newer versions. [...]

This campaign quickly gained international exposure when Wired published a post titled: Norwegian Websites Declare War on IE 6.

But enough with the background of this campaign. Joining the campaign is pretty simple: you just have to add a few lines of HTML + CSS to your blog. No Javascript involved: only conditional comments so that spiders and other browsers will not see it.

If you want to know more on the campaign, there is a wiki to keep you updated with the how the campaign is going: IE6 Do NOT want!

If you are not running IE6, here is a screenshot of it.

CodeClimber-IE6.png

I'll keep this message on the blog for one week or so: it would be interesting to see if the number of IE6 users drops. The average of the last month has been 10% of the overall users.

If you care about the web and own a blog or site, please consider joining the campaign and adding the code for the message in your homepage. Web developers around the World will thank you.

kick it on DotNetKicks.com

Ninject.FilterInjector v1.5: now injecting inside all kind of filters

The first version of my tiny FilterInjector included only the action invoker for ActionFilters.

But ASP.NET MVC has four different filters:

  • Action Filters: executed before and after an Action is executed
  • Result Filters: executed before and after the ActionResult returned by the Action is executed
  • Authorization Filters: executed before an Action is executed, to verify that the current request is authorized
  • Exception Filters: executed when a unhandled exception happens during the execution of the request

Now, thanks to Owen Evans which kindly sent me a patch, the Ninject.FilterInjector can also inject dependencies into all the four kind of filters.

You can download the latest version from my personal Google Code repository, together with a sample ASP.NET MVC website that uses all the aforementioned filters. The instruction to use it in your web applications are outlined in my previous post: Extending Ninject to inject dependencies into Action Filters.



If you are still wondering how fast is ADO.NET vs ADODB

There is this nice paper written by Jason McGuire titled:

Performance Comparison of Microsoft’s ADO and ADO.NET Database Connectors

The quick answer to the question is: inside a .NET application, ADO.NET is 3 to 4 times faster then ADODB when accessing SQL Server.

Well, not a big news you might say, going from .NET to COM and back is obviously a performance problem and also there was a bit of advancements since mid ‘90s, but it’s nice to find someone that published such analysis with such a great degree of details and precision.

If you are not satisfied by the web page that summarizes the results, there is even more detailed report in PDF and even the data points collected during the test runs.

Too bad there is not code to download so that I can run it on my environment and so prove it myself.

And, you really don’t want to know why I was looking for such a performance analysis.

Technorati Tags: ,,,

Oxite: what’s new and how to stay up to date with it

As probably you read somewhere else, a few days ago the Channel9 team released the latest version of Oxite.

If you remember, when it was first released back in December, there was a lot of negative feedbacks, but now it seems like the latest release contains a lot of refactoring. I think I’ll start to play with it.

All the team members have a blog (which runs on Oxite, of course) and they posted some blog posts to explain the new changes.

I think Oxite has a potential if they include the features that are needed by the final end-user (like easy install procedure, update procedure and that stuff).

So I decided to create a folder on my reader, and add all the Oxite related feeds to it. They are the three blogs of above, some of the Codeplex feeds, and the feed of the last team member (Nathan Heskew). If you are interested I created an OPML file that includes all of them.

Some of the members are also on Twitter:

Technorati Tags: ,,,

Interest in ASP.NET MVC is raising

...Or at least this is what we can infer from Google Trends.

GoogleTrendASPNETMVC.jpg

From this graph we can see that searches started in 4th quarter of 2007 (when ASP.NET MVC was first announced) and spikes always happened at each release of the various preview versions. The final ramp coincides with the announcement of the RC and the wait for the actual RC release. I wonder what is going to happen when the RTW is released.

If you browse to the graph, you'll notice a funny thing: the city that performs most searches is Redmond, where the MS offices are. Either they are constantly looking for new blog posts on the topic or other offices in the company listen to that product and go and look what it is about.

If we compare the volume of searches of ASP.NET MVC with the one of Ruby on Rails, you notice that the interest in RoR is dropping since mid 2007, and now it is half of what it was in 2006. This might either mean two things: the interest in RoR is really dropping after the excitement of the first period, or everybody that was interested already knows everything and rarely look on the web for informations (which also mean that there are little new people embracing it as notoriously RoR documentation is not that good).

GoogleTrendASPNETMVCvsRoR.jpg

In the last month searches for ASP.NET MVC are just half the one for RoR.

GoogleTrendASPNETMVCLastMonth.jpg

Let's wait for "a little before MIX" (as at MIX there are no session planned for ASP.NET MVC, so I doubt the RTW will be released at MIX) to see how these lines move and if the interest for ASP.NET MVC will overtake the one for RoR.

Thanks to Liam McLennan for tweeting the link to the first graph and giving me the inspiration for this.

kick it on DotNetKicks.com

Extending Ninject to inject dependencies into Action Filters

UPDATE: There is a new version of Ninject.FilterInjector out, version 1.5. You can read more about it on: Ninject.FilterInjector v1.5: now injecting inside all filters 

In the previous posts of the series I explained how to use the Ninject IoC container with ASP.NET MVC and how to adapt the ASP.NET MVC framework to allow injecting dependencies into Action Filters. In this last post of the series I’m going to show you the changes I’ve done to Ninject to make it transparent for the developer to inject dependencies into Action Filters.

What we want to achieve

I want the initialization code of my container to specify the bindings only for the classes of my model and for my services. It doesn’t have to contain infrastructural code.

I want it to be like this:

public override void Load()
{
    Bind<IGreetingService>().To<GreetingServiceImpl>();
}

The code in my previous sample, instead, contained also all the glue to make the custom ActionInvoker method work.

Isolating the changes in an external and reusable library

To make that possible I created an external assembly, and I moved here the custom action invoker that, before invoking the actions, inject the dependencies into the filters.

namespace Codeclimber.Ninject.FilterInjector
{
    public class NinjectActionInvoker : ControllerActionInvoker
    {
        private readonly IKernel _kernel;

        public NinjectActionInvoker(IKernel kernel)
        {
            _kernel = kernel;
        }

        protected override ActionExecutedContext InvokeActionMethodWithFilters(
            ControllerContext controllerContext,
            IList<IActionFilter> filters,
            ActionDescriptor actionDescriptor,
            IDictionary<string, object> parameters)
        {
            foreach (IActionFilter actionFilter in filters)
            {
                _kernel.Inject(actionFilter);
            }

            return base.InvokeActionMethodWithFilters(
                controllerContext, filters, actionDescriptor, parameters);
        }
    }
}

The other piece of code that is needed for injecting into filter is the one that configures each controller to use the aforementioned ActionInvoker. If you recall from my previous post, it was pretty repetitive, boring and potentially long in case of many controllers. So I modified the AutoControllerModule that comes with Ninject 1.5 to have it inject the custom ActionInvoker as well, and I named it AutoControllerModuleWithFilters.

The only method I changed is the one that loops through all the types of the assembly and register its bindings.

private void RegisterControllers(Assembly assembly)
{
    Bind<IActionInvoker>().To<NinjectActionInvoker>().Using<SingletonBehavior>();
    foreach (Type type in assembly.GetExportedTypes())
    {
        if (!type.IsPublic || type.IsAbstract || type.IsInterface || type.IsValueType)
            continue;

        if (!typeof(IController).IsAssignableFrom(type))
            continue;

        string name = GetNameForController(type);

        Bind(typeof (IController)).To(type).OnlyIf(ctx => CheckControllerName(ctx, name))
            .InjectPropertiesWhere(p => p.Name == "ActionInvoker");
    }
}

The rest of the class is the same as the original one.

How to use the FilterInjector library

I packaged the two classes above in their own assembly, so all you have to do to inject dependencies into ActionFilter is:

  1. Download the Codeclimber.Ninject.FilterInject library (bin and source)
  2. Create a reference to the Codeclimber.Ninject.FilterInject.dll
  3. Configure Ninject using the AutoControllerModuleWithFilters class instead of the AutoControllerModule (after importing the Codeclimber.Ninject.FilterInject namespace)

With this in place you can configure all your dependencies as you always did, and don’t care about whether the dependency needs to be injected into a controller or an action filter. The following code is part of the Global.asax.cs file:

...
using Codeclimber.Ninject.FilterInjector;
...

public class MvcApplication : NinjectHttpApplication
{
    protected override void RegisterRoutes(RouteCollection routes)
    {
        //Your routes here
    }

    protected override IKernel CreateKernel()
    {
        var modules = new IModule[]
             {
                 new AutoControllerModuleWithFilters(Assembly.GetExecutingAssembly()),
                 new ServiceModule(),
             };
        return new StandardKernel(modules);
    }
}

internal class ServiceModule : StandardModule
{
    public override void Load()
    {
        Bind<IGreetingService>().To<GreetingServiceImpl>();
    }
}

As you notice, this code is exactly the same of the one used to configure an ASP.NET MVC application to use Ninject.

Where to get the library

I sent the patch to Nate Kohari, and I hope he is going to include this feature into the official release of Ninject, but in case he doesn’t, I published this small piece of code on my SVN repository on Google. You can download the binary distribution, the source distribution, the sample application, browse the source code online, and if you find bugs or have suggestions, please post them on the online tracking tool.

UPDATE: There is a new version of Ninject.FilterInjector out, version 1.5. You can read more about it on: Ninject.FilterInjector v1.5: now injecting inside all filters 



kick it on DotNetKicks.com

A big applause to Mindscape

Just a quick note to congratulate with JD, JB and Andrew Peters for the big achievement: Mindscape, the company behind Lightspeed, was named as the second best NZ startup of 2008.

A big achievement for these three guys, that created all this with no external funding and just three full-time employees (themselves).

I was lucky to meet all them in person while I was in NZ, and besides being smart guys, they are also very nice persons.

Again, my best compliments and good luck for the future.

Video explanation of jQuery

Lately I’m trying to get deeper into jQuery and during one of mine information hunting sessions I found this awesome video presentation of jQuery, by Ben Nadel.

It’s a 1h45min screencast that covers all the aspects of jQuery, from the simplest UI Effects to the more complicate Ajax requests, the powerful data() method till plugin authoring.

I think it’s a very interesting presentation to watch even if you are experienced jQuery user as it explains the concepts behind it in a very clear way. In particular, I really loved how he explained closures

Or you can just grab the slides and demos and skim through the slides.

Just one recommendation: the size of the video is pretty big, I guess it’s 800x600, so make sure you watch it in full-screen mode and that you have enough bandwidth on your side.

Here is the link to the video: An Intensive Exploration Of jQuery With Ben Nadel

Technorati Tags: ,,

Introducing Bespin, online collaborative code editor

Bespin_Logo.png

After word processors, mockup designer and mind mapping tool, it's the time of code editors: yesterday the Mozilla Labs announced Bespin, a online web-based collaborative code editor.

It's still a very early alpha release, so many things are still missing and are waiting to be implemented. The high level features of Bespin are:

  • Ease of use
  • Real-time collaboration
  • Integrated command line
  • Extensible
  • Fast and responsive
  • Accessible from anywhere

At the moment the collaboration and the extensibility are yet to be implemented, but all the rest is already there. I was really impressed by how fast and responsive is the editing window, even with very big files. To make this possible they said they rewrote everything using the canvas object instead of relying on textboxes or the other editing API. And, as frosting on the cake, they have a very cool dark color schema.

webkit-editor-medium.png

If you want to know more, make sure you read the official announcement, the project site, watch the video presentation, and then try it out by yourself.


Introducing Bespin from Dion Almaer on Vimeo.

Do you wanna be the Picasso of programming? First learn the rules, and only after break them

UPDATE: Stackoverflow #41 is out. I bet it's going to be the most listened episode ever.

This morning I woke up, and suddenly I was flooded by tweets and posts. All of that were about the latest buzz of the moment: “Are Jeff and Joel going crazy or are they just playing going crazy?”.
I just want to think that, at least Jeff, is just playing the devil’s advocate, and giving a voice to the silent crowd that thinks that “getting things done” and “ship the product/project” is more important than crafting a good piece of software that can be maintained for long time. I HOPE it’s just that, and he is exaggeratedly pushing the opposite to try and reach a better balance between the two opposites.

First thing I want to make clear my position on the ALT.NET thing. When ALT.NET came out two years ago or so, I was skeptical at first, because I thought that, while the idea behind it was great (and it proved to be great), it was useless because 90% of the developers don’t care about their job and thus they do the least amount of work in order not to get fired. But then I decided to try and spread the word myself.

What happened?

But going back to the topic of that post. I’ve an opinion about this, so, if you want you can skip directly to it, but if you want to form your own opinion, I’m going to summarize the main episodes of that saga:

  • I think it all started back in October, when Jeff was talking about his experience writing StackOverflow, and said that he didn’t care that much about security and about making the software flexible because he wanted to push the site out as quickly as possible. Scott almost felt off this chair when he heard that, but Jeff assured that the refinements (aka refactoring) would have come later.
  • Then, still on Hanselminutes, Bob Martin talks about the SOLID principles, and how they help writing good, maintainable, testable software with almost no effort. IMHO the best explanations of these principles I’ve ever heard, really recommended
  • In StackOverflow Podcast #38, Joel, commenting on the just mentioned podcast, states :“Quality just doesn’t matter that much” and also that this is leading to “extremely bureaucratic programming”, and many other comments like this.
  • This podcast obviously started to wake up the nest of hornets that is the community, but the first that really noticed and commented about this outing was Mr. Uncle Bob in person, which answered with the post: “Quality Doesn’t Matter That Much” — Jeff and Joel. He also wrote an “An Open Letter to Joel Spolsky and Jeff Atwood” to try and bring is points on. He also suggests to be invited to talk at a future episode of the show, but till now nothing happened yet and it was interviewed in episode Stackoverflow #41.
  • But the proverbial last straw was Jeff’s answer to Bob: The Ferengi Programmer. I think he is correct when he says that you don’t have to stand on giant’s shoulders but that you have to have a critic mind, and adapt to the environment. But he speaks to 124 thousands readers, the vast majority of which don’t read other blogs (Codebetter only has 30K, 1/4th of Jeff’s readers), and I guess they didn’t hear anything SOLID before. What they got (even if Jeff didn’t explicitly said) is that Principles, Pattern and all that stuff is useless and cumbersome, and only slows you down when you have to write code that has to ship.
  • Obviously this post didn’t go unnoticed as the others, and quite a few people wrote their thought about that:

We are like house builders at the time of Egyptians

I think it’s good that Jeff and Joel started this conversation, because it might help our industry grow a bit.
We are (to continue with Rob’s analogy) in the position of the first house builders at the times of the Egyptians: we are still experimenting and trying to find the best way to build software. Some Egyptian builders applied all the principles they had at the time, using good stones, with the correct design. Other used cheap wood, hold together by ropes, and the house was build just putting on piece on top of the other. The pyramids costed more money and took more time than the wooden house, but they still stand after 4.000 years, while the other houses probably went destroyed at the first sand storm. After thousand of years of tries and errors, house builders can now apply the right principles for each kind of house so that the quality of the house is balanced by the time and effort spent building it. Probably we will never have a pyramid that can resist 4.000 years (since we understood that applying all the principles can lead to higher costs and longer times), but also we don’t have houses that goes down at the first blow of wind.

But in Software Industry we are still experimenting: probably we will fall in the error of over-using the principles (as it happened with the building industry centuries ago), and then we will move back to balancing the two things, and using only the principles that matter.

The first paintings of the great masters were all classical paintings

But in order to be able to decide which rule and which pattern not to apply, first we have to master all the rules. Only after we have them in our skillset, we can decide whether to apply or not apply a certain principle because we don’t need it. At school I was always taught:

If you look at the history of painting you’ll notice that all great painters’ first paintings were classical paintings. Later they experimented different techniques, and finally they invented their own style.

Last final words

Probably I went to far on this post, and it also took me 3 rewrites to get it to this point, but what I just want to summarize here is that IMHO SOLID principles are good, and that must be in everybody’s toolbox. It’s no point in reinventing the wheel every time. But also pay attention to no overuse them, and apply them with grain of salt. But first... LEARN THE BASICS

kick it on DotNetKicks.com

Technorati Tags: ,,

The first Italian .NET podcast is born

A few days ago DotDotNet, the UserGroup of the Emilia-Romagna, published the first episode of DotCast, the first Italian podcast about .NET.

The first episode is about ASP.NET MVC and about a general discussion on Cloud Computing and Azure. And I'm honored to have been the first guest of this show. I hope this doesn't bring bad luck to the show, as the last I've been the first guest at a show (Mindscape's BrainDump), I've also been the only guest. I hope this time, Igor and Alessandro will keep up with the good work, and give to Italians a reason to be lazy and don't listen to .NET Podcasts in English

Ops... I was almost forgetting the link: DotCast n. 01 - ASP.NET MVC e Cloud Computing (con Simone Chiaretta) (direct MP3 download)

Technorati Tags: ,,,

How to use Ninject to inject dependencies into ASP.NET MVC ActionFilters

Ninject with ASP.NET MVC series

ActionFilters are a great way to encapsulate pieces of functionalities and move them outside ASP.NET MVC Controllers, but they have a problem: it’s very difficult to inject dependencies into them. In this post I want to show you how to use Ninject to inject dependencies into an ActionFilter, first using a simple but not “SOLID”  approach, and then writing some helper classes that allow you not change anything in the way you write your code.

All this post takes for granted that you know how to use Ninject together with ASP.NET MVC. You don’t know, or want to have a refresh, consider reading my previous post on the topic: How to use Ninject with ASP.NET MVC

Why is it difficult to inject dependencies into ActionFilters?

Typically, to inject dependencies into an object, you have to be in control of the instantiation process, either directly or through a Inversion of Control container. But the problem with ActionFilters is that they are .NET attributes, and thus they are instantiated directly by the .NET framework using reflection. This means that you are not in control of the creation process and that you have to inject the needed dependencies later in the process. There a few approaches to solve this problem, and the first we will explore is the easiest but also the worst one.

The scenario

But before digging into the possible solutions let’s see the code of the samples we are going to use in the post. We just want to add to the title of any view a greeting that is retrieved through an external service (the same service used as sample in my previous post about the NinjectControllerFactory for ASP.NET MVC). I’m using the HomeController that is generated by the default ASP.NET MVC Project Template.

using System.Web.Mvc;
using ActionFilterInjection.ActionFilters;

namespace ActionFilterInjection.Controllers
{
[TitleActionFilter] public class HomeController : Controller
{
//Here is your controller implementation } }

Now let’s see the simple but “smelly” way of injecting a dependency inside an ActionFilter.

The static container approach

Since we are not in control of how the action filter is instantiated, the most obvious way of implementing the DI is to create two constructors: one, the default one, used by the runtime and one that is used by you in your unit tests.

public class TitleActionFilterAttribute: ActionFilterAttribute
{
private IGreetingService _service;

public TitleActionFilterAttribute():
this(KernelContainer.Kernel.Get<IGreetingService>()) { }

public TitleActionFilterAttribute(IGreetingService _service)
{
this._service = _service;
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewResult result = filterContext.Result as ViewResult;
if (result != null)
{
result.ViewData["Title"] += " - " + _service.GetGreeting();
}
}
}

All the complexity and the differences from the usual ways of writing such classes lie in the empty constructor: it accesses a static KernelContainer that wraps the real IoC container you are using, gets an instance of the service we want to inject, and then it calls the other constructor with the IoC instantiated service.

The problem here is that you are coupling the action filter with your IoC container: this is bad because you cannot change IoC container without changing all your action filters, and also because then you need to instantiate the IoC container also in your tests (and thus need a valid IoC configuration). And finally, this is THE IoC AntiPattern.

The other way to solve the problem is a bit more complex, but once implemented (once in a lifetime) your ActionFilter will be clean and with no problematic dependencies.

Extending ASP.NET MVC

ASP.NET MVC has an high level of extensibility, and we can change the way it executes ActionFilters by extending the ActionInvoker class, which is the one responsible for executing the actions inside a controller.

Step 1 - Override InvokeActionMethodWithFilters method

The first step is overriding the InvokeActionMethodWithFilters method.

public class NinjectActionInvoker: ControllerActionInvoker
{
private readonly IKernel _kernel;

public NinjectActionInvoker(IKernel kernel)
{
_kernel = kernel;
}

protected override ActionExecutedContext InvokeActionMethodWithFilters(
ControllerContext controllerContext,
IList<IActionFilter> filters,
ActionDescriptor actionDescriptor,
IDictionary<string, object> parameters)
{
foreach (IActionFilter actionFilter in filters)
{
_kernel.Inject(actionFilter);
}
return base.InvokeActionMethodWithFilters(
controllerContext, filters, actionDescriptor, parameters);
}
}

What I do here is intercepting the filters before they are executed and then injecting the needed dependencies. The trick is done by calling the Inject method of Ninject: it takes an already instantiated class and inject all the dependencies configured inside the container.

Step 2 - Change the ActionFilter to use Property Injection

Then we have to slightly change the implementation of the ActionFilter because now we cannot use the construction injection any more (the filter has already been instantiated by someone else). Instead we have to use Property Injection. But it’s an easy fix, it just removes code:

public class TitleActionFilterAttribute: ActionFilterAttribute
{
public IGreetingService _service { get; set; }

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ViewResult result = filterContext.Result as ViewResult;
if (result != null)
{
result.ViewData["Title"] += " - " + _service.GetGreeting();
}
}
}

And the code is also cleaner and shorter.

Step 3 - Set the ActionInvoker in the controllers

As last thing we need to instruct the framework to use our action invoker instead of the default one. This can be done in many different ways:

  • in the default constructor of each controller that needs that customization
  • in a custom controller that you will use as base controller for all your controllers
  • injecting the ActionInvoker inside a custom ControllerFactory

For the first two approaches you would have to write the following line of code in the constructor of your controllers:

this.ActionInvoker = KernelContainer.Kernel.Get<NinjectActionInvoker>();

But this line of code again hides a pitfall: you are using again a static IoC container inside your controller, and this is bad for the same reasons you saw earlier. So, if we want to stick to our dogma (“Do not couple your code with a IoC container”), we need to use a custom controller factory to automatically inject the ActionInvoker. This also has the side benefit of not having to remember to manually set the ActionInvoker in all your controllers.

But since we want to inject dependency in action filters, probably we are also doing the same with controllers, and we already using the NinjectControllerFactory, so we can configure it to inject the action invoker for us, without any other customization.

Step 4 - Configure the Ninject container

The last step is configuring Ninject to handle all these injections (again if you don’t know how to integrate Ninject with ASP.NET MVC, I recommend you go and read my previous article on how to setup an ASP.NET MVC application to use Ninject).

First thing you have to configure the GreetingService:

Bind<IGreetingService>().To<GreetingServiceImpl>();

Then you have to instruct Ninject about how to inject that service inside the ActionFilter. You can do it by just decorating the property that holds the reference.

[Inject]
public IGreetingService _service { get; set; }

Personally I don’t mind using the attribute, even if it slightly couples the filter implementation with Ninject, but I know that someone might not like this, so here is how you can do the same thing, using the fluent API inside the configuration module.

Bind<TitleActionFilterAttribute>().ToSelf()
.InjectPropertiesWhere(p => p.Name == "Service");

The line of code says that whenever someone asks for the TitleActionFilterAttribute class, the container should give him that same class and then inject into it the property named “Service”.

Then we have to specify that every time someone asks for an IActionInvoker, it should receive an instance of the custom action invoker we developed before.

Bind<IActionInvoker>().To<NinjectActionInvoker>().Using<SingletonBehavior>();

I’m using the SingletonBehaviour because the action invoker doesn’t maintain any state, so it’s safe to treat it as singleton, and gain a few milliseconds during the instantiation of the class.

The last configuration needed is the one that injects the custom invoker inside every controller.

Bind<IController>().To<HomeController>()
.Only(When.Context.Variable("controllerName")
.EqualTo("Home"))
.InjectPropertiesWhere(p => p.Name == "ActionInvoker");

If you remember from my post about the AutoControllerModule of Ninject, this is what we used to do before the automatic controller module. But now we want to expand the configuration to specify that, after Ninject created the controller, it also has to inject a dependency in the property named “ActionInvoker”. And so we need to do it again, one per controller. Hopefully Nate will come to the rescue and implement this directly into Ninject.

Wrapping up

In this post we saw that extending the ASP.NET MVC framework is the easiest way to inject dependencies into an action filter. And it requires just 3 steps:

  1. Creating a custom ActionInvoker and overriding its InvokeActionMethodWithFilters method
  2. Specifying the custom ActionInvoker inside the controller
  3. Configuring the IoC container

But it’s all boring and repetitive stuff, so, to help you get the most out of this, I extracted the customizations to an external assembly file and I’m also thinking about downloading the source of Ninject and writing a patch to bring this enhancement inside the Ninject integration pack for ASP.NET MVC.

The goal is that you don’t have to do anything more than just designing your action filters to accept dependencies from outside, and configure that dependencies in the IoC configuration.

But this post turned out a bit longer then I initially thought, so I’ll cover this in another post later this week, so if you haven’t already, consider subscribing to my updates via RSS.

While you wait for the easy path, you can start playing with this sample downloading the sample project that contains all the samples.

kick it on DotNetKicks.com

Look Ma, I’m on the TV (on Channel9)

Channel9Inteview

Last Friday I headed to Microsoft Italy offices in Segrate (with my Vespa and under a pouring rain), for being interviewed by Pietro Brambati, Italian Developer Evangelist, about ASP.NET MVC.

You can watch the video (in Italian) on Channel9.

I want to thank Pietro and the Italian DPE team for the interview and for the nice tech chat we had during the day.

Technorati Tags: ,,

How to use Ninject with ASP.NET MVC

By default, the ASP.NET MVC framework instantiate controllers calling their default constructor. This makes using Dependency Injection impossible. But, as almost everything inside that framework, the logic with which a controller is instantiated can be replaced with you own logic. This can be done creating your own ControllerFactory, which is pretty simple. But if you are using one of the many popular DI/IoC libraries, that task is even simpler, since there are already custom controller factories for almost all the IoC libraries available. In this post we are are going to see how to use the ControllerFactory that delegates to Ninject the creation of your controllers.

This post assumes that you know a bit of how to use Ninject and how to configure it. If you don’t know, first head to the Niject Dojo and read about the basics.

What are we trying to accomplish?

Before looking at how to setup the environment, let’s see the classes that are going to be handled by the IoC container. We want to greet the user of our page, and we want the greeting retrieved by an external service.

First is the external service and its interface:

public class GreetingServiceImpl : IGreetingService
{
    public string GetGreeting()
    {
        return "Hello from the Greeting Service concrete implementation!";
    }
}

public interface IGreetingService
{
    string GetGreeting();
}

Then is the HomeController, which displays the greeting based on the value returned by the IGreetingService.

public class HomeController : Controller
{
    private readonly IGreetingService _service;
    public HomeController (IGreetingService _service)
    {
        this._service = _service;
    }

    public ActionResult Index()
    {
        ViewData["Message"] = _service.GetGreeting();

        return View();
    }
}

And now on with IoC inside ASP.NET MVC.

A bit of theory

There are three steps involved in setting up an ASP.NET MVC application to use a custom controller factory:

  1. you need to register the controller factory with the application
  2. you need to configure the IoC container for all your controllers and dependencies
  3. you need to initialize the container

Registering the controller factory

The first step is pretty easy, and it’s the same for all the controller factories.

ControllerBuilder.Current.SetControllerFactory(typeof(NinjectControllerFactory));

Setup the controller factory

The second and the third steps vary by the IoC container you are using: it can be an XML file that contains all the classes and their dependencies, it can be a bunch of attributes with which all your controllers are decorated, it can be a few lines of code that configure the container via a fluent API. With Ninject it’s the latter.

MvcContrib.Ninject.NinjectKernel.Initialize(
    new ControllerModule(),
    new ServiceModule()
);

Ninject simple configuration

After you configured the external services (in the sample above the configuration is contained inside the ServiceModule class), you have to configure each controller, specifying under which condition the given class should be initialized.

public override void Load()
{
    Bind<IController>().To<HomeController>()
        .Only(When.Context.Variable("controllerName")
            .EqualTo("Home"));
}

In the sample the HomeController class is returned to the caller only when the controller name is “Home”.

As you can imagine, if your application has 20 controllers, setting up everything by hand can be tedious and error prone. But this was exactly what you had to do to setup Ninject using the custom controller factory that is part of MvcContrib and that targets Ninject pre-1.0 (actually it still is, but is marked as Obsolete, so it’s like it’s not there anymore).

How to do it with Ninject “trunk” (v1.5)

But things are easier if you are brave enough to use the “trunk” of Ninject (it’s v1.0 plus many new features).

You don’t need to register the controller factory yourself anymore, and you don’t need to setup each controller manually.

Actually using the trunk of Ninject is not very risky, as it’s mainly bug fix and new small features, and it’s very stable. The only problem is that you have to build it yourself. But let’s see how this is done.

If you want to get straight to coding you can skip the next two steps and just download the version I built for you. Otherwise, here is how to get the latest code and build it.

Getting the trunk

The first thing you have to do is, if you didn’t do it already, getting the latest version of the trunk from the Google SVN repository. (The direct url for the trunk is: http://ninject.googlecode.com/svn/trunk/)

Building the trunk

Now that you got the trunk, first you must update the ASP.NET MVC libraries and then just double-click on the “build.cmd” file: that will start the build process, and after a minute or so you will see a new folder appear, containing the compiled binaries.

For the lazy people

If you don’t want to go through the hassle of getting the trunk, updating references to ASP.NET MVC RC1 and then building, I already went through all these steps and you can download the version I built here.

Rev 119 updated with ASP.NET MVC RC1 references

But beware that this is not the official release of Ninject, and you should check online to see if a new official version is released.

ReferencesAdding references

To use Ninject with ASP.NET MVC you just need three of the many dlls that comes with the package:

  • Ninject.Core
  • Ninject.Conditions
  • Ninject.Framework.Mvc

You have to copy them to a folder inside your solution and reference them inside your ASP.NET MVC project.

Setting up the container

All the setup goes into the Global.asax.cs file of your application. First I’ll show you the complete code, and then I’ll discuss the details.

public class MvcApplication : NinjectHttpApplication
{
    protected override void RegisterRoutes(RouteCollection routes)
    {
        //Here goes routing setup
    }

    protected override IKernel CreateKernel()
    {
        IModule[] modules = new IModule[]
                        {
                            new AutoControllerModule(Assembly.GetExecutingAssembly()),
                            new ServiceModule()
                        };
        return new StandardKernel(modules);
    }
}

internal class ServiceModule : StandardModule
{
    public override void Load()
    {
        Bind<IGreetingService>().To<GreetingServiceImpl>();
    }
}

The first thing that you notice is that the class inherits from NinjectHttpApplication instead of HttpApplication

public class MvcApplication : NinjectHttpApplication

Then, you might notice that there is no Application_Start method: it is hidden inside the base class, which also takes care of registering the controller factory with the framework. You can still specify the routing rules inside the RegisterRoutes method (it is the usual register route method, just with a leading “override” clause).

And finally you need to provide the configuration inside the method CreateKernel.

But there is new player on the field now: it is the AutoControllerModule class that automatically scans the given assembly and creates the configuration for the controllers it finds.

new AutoControllerModule(Assembly.GetExecutingAssembly())

So, instead of manually configuring all your controllers by hand, you can just put this line and everything will auto-magically work. Cool, isn’t it?

Obviously we had to configure the external dependencies, but that is the tax we have to pay to use any IoC container.

Where to do go from here

I really encourage you to give that post-release version of Ninject a try, as it includes this cool integration pack with ASP.NET MVC and few other improvements and bug fixes to the library. And, to my experience with it, it’s pretty stable.

If you want to try it for yourself all the samples, I packaged the Visual Studio solution, and you can download it.

I hope you enjoyed reading this tutorial as much I enjoyed writing it and playing around with Ninject, which, IMHO, is one of the best IoC containers available for the .NET platform (and, without doubts, the one with the coolest website and mascot).

I’m planning on writing more about Ninject and it’s integration with ASP.NET MVC so, if you hadn’t already and you liked that post, please consider subscribing to the feed.

kick it on DotNetKicks.com

Ruby <3 .NET: recordings and material are online

I just published the first two recordings from the Italian ALT.NET Conference of last Saturday.

The first, and probably more interesting because the session was in English, is Ivan’s one about IronRuby, titled “Ruby <3 .NET”.

And the slides and demo are available on the SVN repository for the conference.

I also published the last session of the day, that was about Fitnesse and acceptance tests in general, held by Jacopo Franzoi. Here you can see the video (in Italian, sorry)


Test di accettazione (Fitnesse) from Piyodesign on Vimeo.

And, as for the IronRuby session, you can find the demo and the instruction to get them running (which are in English), on the SVN repository.

It was fun to record and encode the movies, and really have to say that I was able to capture from my DV camera directly to an external firewire Hard Drive through iMovie. That’s a really cost effective way to record 6 hours of videos, without buying 6 DV cassettes than I’ll never use again.

PS: If you notice something strange going on, is the “demo mode” of the camera that after a certain time of inactivity (camera turned on but not recording) start bugging. I didn’t find a way to disable it on time for the conference. Sorry for the nightshots, posterized frames and all that crappy stuff.

Technorati Tags: ,,