Saturday 30 March 2013

Dependency Resolution in ASP.NET MVC3/4 with Ninject

The topic for this post is setting up the Ninject Inversion of Control (IoC) container in your ASP.NET MVC3/4 applications. I'm assuming the reader has familiarity with the following concepts:

  • Programming to an interface (or contract)
  • The IoC programming technique
  • Dependency injection
  • IoC containers

The intention is for this post to serve as a useful reference for ASP.NET MVC developers who want to get an IoC container (specifically Ninject) up and running swiftly with the MVC framework.

When working on a new MVC project, one of my first steps usually involves setting up an IoC container. I've typically used Ninject as my IoC container due to its ease of setup and intuitive fluent API. As of ASP.NET MVC3, there is the option of using the Ninject extension for MVC3 (wrapped up in a NuGet package called Ninject.MVC3). This option is simple to setup and you'll typically have little reason to use another approach. Another option is to write your own implementation of the IDependencyResolver interface. In this scenario, you'll implement this interface (which again is quite simple with Ninject) and then hook your custom resolver into the framework for it to use. In a nutshell, the MVC framework will use your custom IDependencyResolver implementation as a first port of call to resolve any required dependencies.

In this post, we'll go with the former option.

Using the Ninject.MVC3 NuGet Package

As mentioned, the Ninject.MVC3 NuGet package is an easy way to get Ninject up and running in your project. The first step is to get the package installed in your solution. I'm using Visual Studio 2012 so the steps may differ slightly depending on what version of the IDE you're running on. Right click your MVC solution node in Solution Explorer. Select the "Manage NuGet Packages for Solution" option in the context menu.



This will bring up the NuGet package manager dialog. In the top right, you should see a text box with the watermark "Search Online". Type "Ninject" and hit enter. In the middle pane, you'll see the Ninject.MV3 package, select it and click the Install button.



At this point, the NuGet package manager will have done all of the hard work. If you expand the App_Start folder in your solution, you'll find a new file called NinjectWebCommon.cs.



This file contains a static class definition and a number of static methods. The methods that you're interested in are the CreateKernal and the RegisterServices methods. If you have had experience with Ninject in the past, then you'll be at home with what the CreateKernal method is doing. It creates an instance of the StandardKernal (the default implementation of Ninjects IKernal interface). The StandardKernel is the class you'll use to map (or in Ninject terminology "bind") interfaces to the implementations that you want to use. This is done by using the generic methods Bind and To on the kernel object, where you pass your interface and implementation, respectively, as type parameters. You'll notice that the CreateKernal method makes a call to a method named RegisterServices. This is the method where you'll register your bindings with Ninject.

private static void RegisterServices(IKernel kernel)
{
    // Register your ninject bindings here!
}
Now that Ninject is setup in the project, we'll try and inject a dependency through a controller constructor. In this example, imagine you have a simple logging interface, defined as:

public interface ILogService
{
    void Log(string message);
}
We then have an implementation of this interface:

public class DebugLogService : ILogService
{
    public void Log(string message)
    {
        System.Diagnostics.Debug.WriteLine(message);
    }
}
Imagine further that we now wanted various actions in our HomeController to log to the debug output. With dependency injection, one way to inject our DebugLogService implementation into our HomeController would be through the constructor - as follows:

public class HomeController : Controller
{
    private readonly ILogService _logService;

    public HomeController(ILogService logService)
    {
        _logService = logService;
    }

    public ActionResult Index()
    {
        _logService.Log(
            string.Format("Index() called at {0}", 
                DateTime.Now));

        return View();
    }
}
If you're following the steps and you now run your web application, you'll get a runtime exception stating that there was an error activating ILogService. This is good, as it tells you that Ninject tried to create an instance of the HomeController, but failed in doing so because the HomeController has no default constructor. The constructor that it does have, however, has one required parameter (logService) that Ninject has no type bindings for. We'll now go back to the static RegisterServices method in the NinjectWebCommon class and add the binding as shown below:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ILogService>().To<DebugLogService>();
}
If you now run the application, you'll find that the HomeController is successfully being instantiated with Ninject passing an instance of the DebugLogService class through to the constructor. You can verify this by looking at the output window for the log entry.



And that's it - you'll now follow this pattern for registering your bindings in the RegisterServices method and programming to your interfaces for which you have registered bindings. As all of your bindings are registered in a single location, swapping out your implementations with other implementations is an easy job. We can now easily switch all logging to a file by writing a new FileLogService (that implements ILogService) and then bind this to the ILogService in the RegisterServices method.

Sunday 17 March 2013

Binding to PasswordBox in WPF using MVVM

I'm currently working on a Windows Presentation Foundation (WPF) client application that adheres to the Model View ViewModel (MVVM) design pattern. Having had a lot of experience with .NET WinForms, the WPF learning curve wasn't so steep. The main areas I initially concentrated on were getting to grips with XAML, then concepts such as data binding, commands, dependency properties and attached properties. It's the last of these that helped in resolving the problem I had with the PasswordBox control and view model binding.

In WPF, data binding enables you to hook a specific property in your data context (in my case, the view model) to a property on a user interface control. For example, the following XAML markup shows how the Text property on a TextBox can be bound to the FirstName property on the view model:
<TextBox Height="23" 
         Width="120" 
         Text="{Binding Path=FirstName, Mode=TwoWay}" />
As the Mode is set to TwoWay, any text changes by the user will result in the FirstName property being updated in the view model, likewise, any programmatic change to the FirstName view model property will result in the user interface being updated (provided that your view model implements the INotifyPropertyChanged interface and the setter of the FirstName property raises the OnPropertyChanged event). In my case, I had a PasswordBox control in my XAML markup that needed binding to a view model string property named Password. Initially I tried this in XAML:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             Password="{Binding Path=Password, Mode=OneWay}" />
However, the Visual Studio XAML designer immediately underlined the 'Password="{Binding...' line and stated the error:
A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
As the binding error message alludes to, it turns out that the Password property on the PasswordBox control is a standard .NET CLR property and this was a deliberate security-based design decision by Microsoft to prevent plain text passwords from sitting around in memory. In my case however, having the password sit in memory wasn't an issue.

Of course, if the application I was working on wasn't using MVVM, then I could easily have picked up the user entered password in the code-behind in a button click event handler (e.g. this.userPasswordBox.Password would return the plain password). But because the application was adhering to MVVM, the code-behind was pretty much empty (except for the usual constructor boilerplate code). Instead, all of the UI "events" were being handled by the view model via command objects exposed as public properties. This therefore made retrieving the password from the PasswordBox and assigning it to the view model Password property an annoyingly interesting problem!

After doing a bit of research on the web, I found a couple of solutions.

  • Pass the PasswordBox control to the view model: In this solution, the PasswordBox control itself is passed back to the view model via a command parameter (which is hooked up to the "OK" button). The method that handles the command then gets the PasswordBox instance via an object type parameter which can be cast back into a PasswordBox. You can then retrieve the password easily through the PasswordBox.Password property.
  • Use attached properties to enable binding: In this solution, attached properties (a special type of dependency property) are created, enabling you to use them on the PasswordBox control and bind to your view model property.

The first solution above works but I wasn't too happy with passing a UI component to my view model - it violates the MVVM design pattern principle of decoupling the view from the view model. I went for the second option as it enabled binding to the PasswordBox.Password property (albeit indirectly) and didn't violate the use of MVVM in the process.

To get this working, take a look at the static PasswordBoxAssistant class on Samuel Jack's interesting blog. The class defines the attached properties that you can then use in your XAML markup, in my case, it resulted in the following markup:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             ap:PasswordBoxAssistant.BindPassword="true"
             ap:PasswordBoxAssistant.BoundPassword=
                "{Binding Path=Password, 
                  Mode=TwoWay, 
                  UpdateSourceTrigger=PropertyChanged}"
 
/>
As shown in the markup above, you'll need to import the namespace that the PasswordBoxAssistant class is defined in and add an alias to it (in my case "ap"). Having done that, it's finally just a case of using the attached properties to wire up the binding to your view model property.

Friday 1 March 2013

The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialisation. Lazy initialisation is where you intentionally delay the creation of an object that is expensive to create.

You would typically want to use lazy initialisation in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialise the object if it is required. One reliable place where you may have seen the lazy initialisation tactic being used is in an implementation of a singleton class - which will have a method or property that returns the singleton instance, for example:

public MySingletonClass GetInstance()
{
    if (_singleton == null)
        _singleton = new MySingletonClass();

    return _singleton;
}
The logic before the return statement is an example of lazy initialisation, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don't know if MySingletonClass is expensive to create, and we don't particularly care as we're using lazy initialisation to prevent multiple instances of MySingletonClass from being created.

If we now go back to the mainstream use for lazy initialisation, where we want to delay instantiation of expensive-to-create objects, you could adopt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and when ever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.

The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we'll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it'll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may therefore look like:

public class Order { }

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        // Simulate getting lots of orders from an
        // order repository
        Orders = Enumerable
            .Repeat<Order>(new Order(), 200)
                .ToList();
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As the code indicates, it would be expensive to instantiate a Customer object if we didn't require the order information contained within it. This is where you would apply the concept of lazy initialisation. In this case, we'll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public Lazy<List<Order>> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        Orders = new Lazy<List<Order>>(() => {
            // Simulate getting lots of orders from an 
            // order repository 
            return Enumerable
                .Repeat<Order>(new Order(), 200)
                    .ToList();
            }
        );

        Debug.WriteLine(this);
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I've also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.

var customer = new Customer(1);
                       
Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

// Ok, we now want the orders...
var ordersForCustomer = customer.Orders.Value;

Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

Debug.WriteLine("Customer {0} has {1} order(s)", 
    customer.Id, ordersForCustomer.Count);
If you execute the code above using the updated Customer class, you'll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is:

I'm customer with id 1
Are orders instantiated? False
Are orders instantiated? True
Customer 1 has 200 order(s)
Notice that when the Customer object was initialised, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn't yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) - this forces our lazy object to instantiate. We re-query the IsValueCreated property which now returns True and finally we output the order count to show that the orders have been successfully lazily-loaded.