Decaying Code

Where code comes to die

Introduction to Ninject 2.1

Links

What is Ninject?

Ninject is a Inversion of Control (a.k.a IoC) tool that allows you to map Interfaces to Implementations.

An IoC main job is to instantiate an object that is linked to a requested type. An IoC tool will also control the lifetime of those objects to allow more flexibility in the invocation of them.

How do I use it?

Well first, you have to download the original version from the Ninject Github site.

There, you are met with many different options that will allow you to match your need. It is important to notice that if you are using a specific Ninject Extension, it requires the same version of Ninject to be used (packaged inside the Extension’s zip file).

For the demo purpose, we’re going to use the .NET 4.0 version of Ninject.

Prerequisites

Now let’s try to build a simple project. We’ll create a solution containing only a Console application for demo purpose and add the Ninject reference.

NinjectConsoleProject

Then we need an interface and a class implementing that interface to simulate a real-life situation.

public interface IConsoleOutput
{
    void HelloWorld();
}

public class MyConsoleOutput : IConsoleOutput
{
    public void HelloWorld()
    {
        Console.WriteLine("Hello world!");
    }
}

Once this is implemented, we have everything we need to implement a simple demo for Ninject.

Ninject Implementation

So in a highly coupled application, we would see a direct invocation of MyConsoleOutput and it would end there. However, when that class change or if we want to test that class, it will be impossible to do so without invoking it. By coding directly against an interface or an abstract class, it allows us to decouple the implementation and the contract.

So next, we need to implement the standard ninject container that will hold “Bindings”. Those bindings represent the link between an interface and it’s implementation. Under Ninject, the container is called a Kernel and is represented by the class StandardKernel.

var kernel = new StandardKernel();

Then we create the binding between IConsoleOutput and MyConsoleOutput.

kernel.Bind<IConsoleOutput>().To<MyConsoleOutput>();

Finally, we’ll request an instance of IConsoleOutput and execute it. You should receive a “Hello world” on your console.

var output = kernel.Get<IConsoleOutput>();
output.HelloWorld();

Well that was easy! But what if it’s a dependency on another object? Like this:

public class Service
{
    private readonly IConsoleOutput _output;

    public Service(IConsoleOutput output)
    {
        _output = output;
    }

    public void OutputToConsole()
    {
        _output.HelloWorld();
    }
}

Requesting the Service like this and executing it will lead to the same result.

var service = kernel.Get<Service>();
service.OutputToConsole();

That’s it!

Conclusion

So Ninject resolves the dependencies of specific objects. What isn’t shown in this demo is that dependencies on dependencies are also going to be resolved. This allows you to build object graph really easily without having to build a factory or have a huge instantiations call. This allows you to have objects that are loosely coupled and highly testable.

Of course, Ninject isn’t the only tool that can do that job but so far, I’ve found it to be the easiest.

The alternatives

Using Ninject with ASP.NET MVC 3 dependency injection

Ninject is my favorite container for doing dependency injection. However, it always seemed a bit complicated to use with ASP.NET WebForms.

Things have improved with ASP.NET MVC 1 of course but now, with the release of ASP.NET MVC 3, things have become way easier to do.

Here is what my Global.asax.cs looks like when I want to register an IoC tool for ASP.NET MVC 3:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterDependencyResolver();
}

private void RegisterDependencyResolver()
{
    var kernel = new StandardKernel();

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

Well that look easy enough no? Well, to be fair… NinjectDependencyResolver doesn’t exist. It’s a custom class that I created to allow the easy mapping of the Kernel.

The only thing it needs is the Ninject StandardKernel. Once all the mappings are done, we give the kernel to the resolver and let MVC handle the rest.

Here is the code for NinjectDependencyResolver for all of you to use:

public class NinjectDependencyResolver : IDependencyResolver
{
    private readonly IKernel _kernel;

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

    public object GetService(Type serviceType)
    {
        return _kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _kernel.GetAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }
}

Updated to .NET Blog Engine 2.0

Well hello everyone,

So I updated from Blogger to .NET Blog Engine 2.0. The transfer was painful indeed. Blogger isn’t supporting a pure BlogML markup and I had to convert everything to the new format. Including of course fixing all the slugs and the old url so that they could still works.

Since this new engine will allow me more flexibility, the frequency of posts shall increase.

See you all later!

Tip & Trick : Intellisense for Javascript in Visual Studio 2010

I know pretty much everyone already knows that but I would love to remember everyone how to get Intellisense working in Visual Studio 2010.

I mainly use jQuery and the API is huge. A bit huge to remember sometimes and I always have the documentation opened in a browser window. To alleviate my pain, I love to use the Intellisense and here is how you get it to work.

First, open your javascript file. Then, drag and drop the file you want to reference at the top of the document.

That's it. You now have Intellisense if a "vsdoc" of your library is available. I'll even throw you something more for you to enjoy. When you declare an event handler for a jQuery element and that you want to access the "event" element. That event is of type jQuery.Event. Just add "/// <param name=variableName type=jQuery.Event />" right after the declaration and it will enable the Intellisense on that variable.

Enjoy!

View Source disabled in Internet Explorer?

Found the fix after scouting the forums.

The main reason is because the caching of SSL pages are disabled and are not on disk. Somehow, IE doesn't allow you to view the source of those pages.

To fix the issue, open the registry and go to the following key:


HKCU\Software\Microsoft\Windows\CurrentVersion\InternetSettings\

There should be a REG_DWORD value with the name "DisableCachingOfSSLPages". The value should be set to "0x00000001". Change it to "0x00000000" and restart Internet Explorer.

This should allow you to view the HTML of your SSL pages when working in a secure environment.

Quick introduction to SOLID

For those who don't know SOLID, it's an acronym of acronym.
SOLID stands for the following:
SRP: Single Responsability Principle
OCP: Open/Closed Principle
LSP: Liskov Substitution Principle
ISP: Interface Segregation Principle
DIP: Dependency Inversion Principle
Bringing those principles together is creditted to Robert C. Martin (AKA Uncle Bob).
You can read about SOLID further on Wikipedia or on Uncle Bob's website.
Please note that I'm also in the process of writing some nice posts on how to apply them to your code.
So stay tuned!

Back to basics: Why should I use interfaces?

So I had this interesting discussion with a colleague about having a clean architecture for a small software he is doing. Since it's his first step among SOLID, I wanted to take it easy see how things were laid out. Since the program was mostly already written, I immediately noticed the lack of pattern and the direct data access in the event of his WinForm application. The conversation went a bit like this:

Me: What is this code with data access on the "OnClick" of your button? Him: Well it's the information I need to execute this command. Me: Do you know the Model-View-Presenter pattern? Because right now, you are mixing "Presentation", "Data Access" and "Business Logic" Him: I've used it before but it's been a while. How do you implement it?

So after showing him the pattern and explaining the basic implementation (because there is a lot of different way to implement this pattern), he asked me the following question:

"Of course, you don't need to use interface everywhere, right?"

But then I went on to explain testability and such but there is something different I wanted to bring to this small discussion and that I wanted to share a bit. When my class have dependencies injected through the constructor, I have 2 choices. Either I depend upon the implementation or the abstraction (interface/abstract). What's the difference and why is it so important?

MyClass depending upon the abstraction of "MyClassDataAccess"

When your class depend upon the abstraction, it can take any class that implement that abstraction (be it abstract class or interface). The implementation can easily be replaced by something else and that is essential in unit testing your logic.

MyClass depending upon the implementation of "MyClassDataAccess"

When your class depend upon the implementation directly, the only that can be sent to this class is this specific implementation. Anything else must derive from this class. This implementation couple the Caller and the Callee really tightly.

Why is it important ?

When you have a class that access services, slow resource (database, disk, etc.) or even a class that you haven't coded yet... an interface should be used. Of course it's not a law. You apply interface/abstract class when you need to decouple an implementation of a system from another system. That allows me to send mocked object and test my requirements/logic. This also bring another advantage that might not be evident at first. Customer changing his mind. When the customer change his mind and do not want to store information in an XML but instead want a database. Or when a customer say to not implement "this part of the system" because it will be available through a service. Etc Etc... Using interfaces and abstract class is the oil that makes the engine of your software turn smoothly and allow you to replace parts by better/different parts without hell breaking loose because of tightly coupled implementation.

ASP.NET MVC - How does the Html.ValidationMessage actually work?

When you create a basic ASP.NET MVC application, you normally will have "Html.ValidationMessage" inserted automatically for you in the Edit and Create views. Of course, if you try to type strings in a number field, it will fail. Same things for dates and such. The good question now is... how does it do it?

Well, the ValidationMessage method only look to see if the model you gave him with the name given have received errors. If it did, it will display the specified message. So now that we covered the "How", I'll show you where it does that.

The answer lies within the DefaultModelBinder that comes activated by default with ASP.NET MVC. The ModelBinder do a best guest to fill your model with the values sent from a post. However, when it can match a property name but can't set the value (invalid data), it will catch the exception and add it as an error in a ModelStateDictionary. The ValidationMessage then picks up data from that dictionary and will find errors for the right property of your model.

That's it! Of course it's pretty simple validation and I would still recommend you to use a different validation library. There is already a few available on the MVCContrib project on CodePlex.

Simple explication of the MVC Pattern

Since the last time I wrote a blog post was more than a few months ago, I would like to start by saying that I'm still alive and well. I had changes in my career and my personal life that required some attention and now I'm back on track.

So for those that know me, I was participating to the TechDays 2009 in Montreal and presenting the "Introduction to ASP.NET MVC" session. I will also be presenting the same session in Ottawa (in fact this blog post is written on the way to Ottawa with Eric as my designated driver).

So what is exactly ASP.NET MVC? It's simply the Microsoft's implementation of the MVC pattern that was first described in 1979 by Trygve Reenskaug (see Model-View-Controller for the full history).

So in more details, the MVC is the acronym of Model, View and Controller. We will see each component and the advantages of having them separated properly.

Model

The model is exactly what you would expect. It's your business logic, your data access layer and whatever else is part of your application logic. This I don't really have to explain. It's where your business logic will sit and therefore should be the most tested part of your application.

The model is not aware of the view or of the controller.

View

The view is where sit your presentation layer for your application. In a web framework, this is mostly ASPX pages with logic that is limited to showing the model. This layer is normally really thin and only focused on displaying the model. The logics are mostly limited to encoding, localization, looping (for grids) and such.

The view is not aware of which controller invokes it. The view is only aware of the model to display.

Controller

The controller is the coordinator. It will retrieve data from the model and hand it over to the view to display. The controller can also be associated to other cross-cutting concerns such as logging, authorization and performance monitoring (performance counter, timing each operations, etc.).

Advantages

Now, why should you have to care about all that? First, there is a clear cutting separation between WHAT is displayed to the user and HOW you get the information to display. In the example of a web site, it become clearly possible to display different views based on the browser, the device, the capabilities of the device (javascript, css, etc...) and any other information available to you at the moment.

Among the other advantages, it's the ability to test your controller separated from your view. If your model is properly done too (coding against abstraction and not implementations), you will be able to test your controller separated from your model and your view.

Disadvantages

Mostly a web pattern than a WinForm pattern. There is currently no serious implementation of the MVC pattern for anything else other than web frameworks. The MVC pattern is hence found in ASP.NET MVC, FubuMVC and other MVC Framework. Thus it limits your choices to the web.

If you take a specific platform like ASP.NET MVC, other disadvantages (that could be seen as advantages) slips in. Mostly, you lose any drag and drop support for server controls. Any grids are now required to be hand-rolled and built manually instead the more usual abstraction offered by the original framework.

Conclusions

Since we mostly require to have a more fine grained control over our view, the abstraction offered by the core .NET Framework are normally not extensible/customizable enough for most web designers. Some abstraction might even become unsupported in the future and thus bringing us to a more precise control of our views. The pattern also allow us greater testability than what is normally offered by default in WebForms (Page Controller with Templating Views).

My recommendation will effectively be a "it depend". If an application is already built with WebForms and doesn't have any friction, there is no point in redoing the application completely in MVC. However, for any new greenfield project, I would recommend at least taking a look at ASP.NET MVC.

Back from vacation and personal changes

Alright! It's been a while. Here is what happened during all that time. I went on vacation in August and I had some changes in my life on the way back.

Just to inform everyone now that the posting should be more common. I'm planned to be on the Visual Studio Talk show somewhere by the end of October. Also, don't miss me at the TechDays 2009 in Montreal and Ottawa! Some pretty nice subjects are talked about!

Talk to you all later!