Dependency Injection in WCF Services with Ninject

Implementing dependency injection in a WCF service can be a little tricky since you don’t directly control the lifetime of the class that implements the interface. However, it is a simple matter to get it working with Ninject. This article by Aaron Stannard and this article by Tony Sneed were pretty useful to find the right direction; however they are a little out of date and the APIs have changed a little.

Part 1: Setting up a test scenario

Create a new WCF Service Application.

wcfdi-createproject

Create a new interface called IRepository:

    public interface IRepository
    {

    }

Create a new class called Repository which implements the IRepository interface:

    public class Repository : IRepository
    {

    }

In your Service1 class, add a constructor that depends on IRepository:

    public class Service1 : IService1
    {
        private IRepository repository;

        public Service1(IRepository repository)
        {
            this.repository = repository;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

Click on Service1.svc in Solution Explorer, and then press F5 to debug the application. Making sure that Service1.svc is focused, causes the WCF Test Client to be launched when you press F5.

Notice the error you get because of the constructor we just added:

wcfdi-parameterlessconstructorerror

Part 2: Setting up Ninject

Stop debugging. Right-click on your solution in Solution Explorer, and select “Manage NuGet Packages for Solution…“. Search Online for “ninject wcf“, and install Ninject.Extensions.Wcf (note that this also installs other related packages that you need):

wcfdi-ninject.extensions.wcf

With that done, right click on Service1.svc and select “View Markup“:

wcfdi-viewmarkup

Configure the service to use the Ninject ServiceHost Factory by adding the line highlighted below:

<%@ ServiceHost Language="C#"
                Debug="true"
                Service="WcfDependencyInjectionNinject.Service1"
                CodeBehind="Service1.svc.cs"
                Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory"
%>

Next, add a new Global Application Class, either via the context menu shown below, or via Add -> New Item… under Web templates, and name it Global.asax:

wcfdi-global-application-class

The Global class you just created must inherit from NinjectHttpApplication, and needs to have a new CreateKernel() method to create the IoC container and configure any types (in this case our IRepository):

// ...

using Ninject;
using Ninject.Web.Common;

namespace WcfDependencyInjectionNinject
{
    public class Global : NinjectHttpApplication
    {
        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<IRepository>().To<Repository>().InSingletonScope();
            return kernel;
        }

// ...

Part 3: Testing

That’s all you need! Once again, select Service1.svc in Solution Explorer, and hit F5 to run the WCF Test Client.

wcfdi-running-correctly

As you can see, the WCF Test Client now connects to the service without any problems. You can put a breakpoint to see how a Repository instance is really being passed into the service’s constructor, and you can invoke service methods via the WCF Test Client.

Windows 10: Switching between Start Menu and Start Screen

Windows 10 Technical Preview brings back the Start Menu (as I wrote in my recent 20-minute review), which replaces the tiled Start Screen that was prevalent in Windows 8 and 8.1.

However, for those who actually liked the Start Screen, you can bring it back by changing a simple setting. First, bring up the Taskbar and Start Menu Properties, either by right-clicking on the taskbar and selecting Properties, or by typing “Navigation” in the Start Menu’s search bar and selecting either of the options provided:

win10-navigation-search

Switch to the Start Menu tab, and then turn off the “Use the Start menu instead of the Start screen” option:

win10-start-screen-setting

You will then be prompted to sign out and sign back in again to effect the change:

win10-start-screen-sign-out

Once you do this, you still go directly into the desktop. But when you click on the Start button or press the Windows key on your keyboard, you are taken to the Start Screen instead of the Start Menu:

win10-start-screen

On Military Intelligence

In a war situation, military intelligence is of vital importance. There are two aspects to this: knowing yourself and the enemy, and knowing the terrain around you.

When you know yourself and the enemy, you are better prepared to face any situation that may arise. Sun Tzu’s “The Art of War” says (emphasis added):

17. Thus we may know that there are five essentials for victory: (1) He will win who knows when to fight and when not to fight. (2) He will win who knows how to handle both superior and inferior forces. (3) He will win whose army is animated by the same spirit throughout all its ranks. (4) He will win who, prepared himself, waits to take the enemy unprepared. (5) He will win who has military capacity and is not interfered with by the sovereign.

18. Hence the saying: If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle.

While knowing your forces and the enemy’s forces is important, knowing the terrain is often even more important. If you’ve played chess before, you’ll know that although each side has full information of the forces at play, it is often a positional advantage that makes the difference. One who often prevailed in battle through terrain tactics rather than strength in numbers was Castruccio Castracani, whose story is narrated in an appendix to Niccolo’ Macchiavelli’s “The Prince” – among other things he used rivers and narrow passes to secure victory against larger forces.

A good chunk of Sun Tzu’s “The Art of War” deals with the various types of terrain and how to use them to your advantage. For one does not obtain the advantage in battle by knowing what terrain is around him, but by knowing how best to use it.

Both aspects of military intelligence (knowing yourself and the enemy, and knowing the terrain) are beautifully illustrated in Chapter 14 of Niccolo’ Macchiavelli’s “The Prince“:

As regards action, he ought above all things to keep his men well organized and drilled, to follow incessantly the chase, by which he accustoms his body to hardships, and learns something of the nature of localities, and gets to find out how the mountains rise, how the valleys open out, how the plains lie, and to understand the nature of rivers and marshes, and in all this to take the greatest care. Which knowledge is useful in two ways. Firstly, he learns to know his country, and is better able to undertake its defence; afterwards, by means of the knowledge and observation of that locality, he understands with ease any other which it may be necessary for him to study hereafter; because the hills, valleys, and plains, and rivers and marshes that are, for instance, in Tuscany, have a certain resemblance to those of other countries, so that with a knowledge of the aspect of one country one can easily arrive at a knowledge of others. And the prince that lacks this skill lacks the essential which it is desirable that a captain should possess, for it teaches him to surprise his enemy, to select quarters, to lead armies, to array the battle, to besiege towns to advantage.

Philopoemen, Prince of the Achaeans, among other praises which writers have bestowed on him, is commended because in time of peace he never had anything in his mind but the rules of war; and when he was in the country with friends, he often stopped and reasoned with them: “If the enemy should be upon that hill, and we should find ourselves here with our army, with whom would be the advantage? How should one best advance to meet him, keeping the ranks? If we should wish to retreat, how ought we to pursue?” And he would set forth to them, as he went, all the chances that could befall an army; he would listen to their opinion and state his, confirming it with reasons, so that by these continual discussions there could never arise, in time of war, any unexpected circumstances that he could not deal with.

Why should we care about military intelligence?

Because just like being well-prepared for war increases the likelihood of victory, being well-prepared for life’s situations increases the likelihood of success.

As a software developer, for instance, one must be familiar with the technologies, the tools, the concepts, the challenges, and even the soft skills.

  • Knowing the tools, technologies and concepts allows you to use the most effective techniques for the situations you will be facing.
  • Knowing the challenges allows you to find the most effective way to address them when you encounter them again in future.
  • Having well-developed soft skills allows you to maintain strong client and internal relationships, allowing you to leverage human resources.

This kind of preparation comes with experience, and so it is important to gain as much experience as we can – not in terms of years, but in terms of scenarios.

Another example is the job market. Just like it is important to keep training for war during times of peace, it is good and healthy to know the job market even if you are stable in your job, because this makes you well-prepared for any time of need, and at the same time keeps you aware of opportunities. Learning the skills commonly requested in job descriptions makes you both more effective in your current job, and competitive when looking to move.

In all aspects of life, be well-prepared by:

  • Knowing your own strengths and weaknesses.
  • Developing your strengths and addressing your weaknesses, through personal development.
  • Knowing your competition (“the enemy”).
  • Knowing the various factors in the scenario (“the terrain”).

C# 6 Preview: String Interpolation

Update 31st January 2015: The syntax for string interpolation has changed as from VS2015 CTP5, as per the example at the end of this article. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Visual Studio 2015 Preview was released last week, and it supercedes the CTPs of what was previously known as “Visual Studio 14”. This VS2015 pre-release comes with a new C# 6.0 feature that wasn’t in the CTPs: string interpolation. Let’s learn about this feature by looking at an example.

I’ve got this Customer class with properties for an Id (integer), FirstName, LastName, and DateOfBirth, and I’ve declared an instance as follows:

            var dateOfBirth = new DateTime(2014, 10, 12);
            var customer = new Customer(1354, "Tony", "Smith", dateOfBirth);

Now, if I want to combine the first and last names into a full name, I can use the typical string.Format():

            var fullName = string.Format("{0} {1}", customer.FirstName, customer.LastName);

But in C# 6.0, I can use string interpolation to take out the placeholders and incorporate the string formatting arguments (in this case the two properties) directly in the string:

            var fullName = "\{customer.FirstName} \{customer.LastName}";

This eliminates the need to have placeholders that match the arguments, which can be a nightmare to maintain when you have a lot of them.

Just like string.Format(), string interpolation allows you to include formatting arguments:

            var dob2 = "Customer \{customer.IdNo} was born: \{customer.DateOfBirth:"yyyy-MM-dd"}";

In the case of the date, I had to put the format string in quotes to prevent the dashes from being interpreted as minus signs.

VS2015 highlights interpolated strings such that the referenced variables are shown as such, and not as part of the string:

vs2015-string-interpolation-highlighting

The actual syntax of string interpolation is going to change. String interpolation has gone through numerous discussions (such as this, this and this), and the development team has decided to change it for the benefit of the language. Quoting the latest C# feature descriptions (PDF):

“Note: This describes the syntax that works in the Preview. However, we’ve decided to change the syntax, to even better match that of format strings. In a later release you’ll see interpolated strings written like this:”

var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";

A 20-minute review of Windows 10 Technical Preview

A few weeks ago, Microsoft released the Windows 10 Technical Preview. Here is a very quick overview of what’s new.

Return of the Start Menu

win10-start-menu

Many of us sorely missed the start menu in Windows 8, and dreaded having to search for programs in a tiled mess. Windows 10 brings back the start menu, combining the traditional search menu functionality we used up to Windows 7 (including searching for programs) and the live tiles from Windows 8.

Windowed Store Apps

Windows Store apps introduced with Windows 8 (formerly known as “Metro” apps, but that name has since been dropped due to legal reasons) have typically taken up the entire screen, which was pretty dumb in cases such as the  music player which really only needs to show a few buttons for its UI.

win10-windowed-apps

That changes in Windows 10, where even the Windows Store apps can be hosted in their own window. This comes with its own limitations though – the minimum width and height of a windowed Windows Store app seem to be what you see in the screenshot above.

Improved Docking

In previous editions of Windows, you could drag a Window to the top edge of the screen to maximize it, or to a lateral edge to dock it to that half of the screen.

win10-docking-1

In Windows 10, you can now dock a window to a quarter of the screen by dragging it into a corner. You can also dock a window to the bottom half of the screen by dragging it towards the taskbar.

win10-docking-2

As you are performing this action, you will even get suggestions on how to fill the remaining space with windows that are already open.

The usefulness of this feature is limited by the fact that windows docked to a quarter of the screen are inevitably quite small, and it does not yet work perfectly – for instance, there is no way to dock the task manager as yet.

Virtual Desktops

I first experienced virtual desktops in Linux almost 10 years ago, and Microsoft are finally adding them to Windows. Better late than never, but still very much appreciated.

win10-virtual-desktops

Virtual desktops are a great way to organize your windows according to different projects you may be working on. I never liked the grouping of taskbar icons by application: if you’re working on three different projects simultaneously, each one might have a Word document open, so it doesn’t really help to group all the Word documents. It’s much more convenient to switch desktop when moving from one project to another.

Improved Selection/Clipboarding in Command Prompt

The command prompt has finally become more usable. You can actually select portions of text normally rather than having to resort to block selection:

win10-command-prompt

…and it is now much easier to copy and paste text in the command prompt. To copy, just select the portion of text you want and press Ctrl+C – the command prompt is intelligent enough to treat Ctrl+C as a clipboard copy if text is selected, or as a process termination signal if no text is selected. Ctrl+V works just fine for pasting text.

Setup Experience

Since the start menu has pretty much replaced the tiled start screen on desktops, it is quite possible to live without the “Metro” experience. However, although the Windows installation routine may have changed a little since Windows 8, the experience hasn’t: it still features an all-Metro interface, attempts to get you to sign into Windows with a Microsoft account by default, and at one point displays some dumb text with nauseating rotating background colours rather than reporting on progress.

win10-setup

Visual Improvements

I noticed that windows now have a soft shadow, which makes the ugly window layout from Windows 8 more bearable:

win10-shadows

Summary

This was just a very quick overview of what has changed in Windows 10, after spending only a few minutes trying it out. I’m sure there are many other features I’ve missed, and this is pre-release software, so take this article for what it is.

My impression is that Windows 10 is nowhere near as horrible as Windows 8, but still does not live up to Windows 7 in terms of user experience.

Pros:

  • Start menu instead of start screen
  • Virtual desktops
  • Docking
  • Windowed Windows Store apps
  • Improved command prompt
  • Visual improvements

Cons:

  • “Metro” still dominates Windows installation
  • Start menu still has live tiles