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

Visual Studio 2015 and .NET 2015 Announcements

.NET goes Open Source

During the Connect(); event on 12-13 November, a few pretty exciting announcements were made. One of the most notable of these announcements came from Scott Guthrie’s keynote speech and his followup blog post: Microsoft are open sourcing the .NET Core Runtime:

“Today I’m excited to announce that we are going even further, and will be open sourcing the .NET Core Runtime.  This will include everything needed to execute .NET code – including the CLR, Just-In-Time Compiler (JIT), Garbage Collector (GC), and core .NET base class libraries.”

Microsoft have already been working hard to open source the .NET server stack, and on top of that, they will be releasing official distributions of .NET Core for Linux and Mac.

From the Microsoft news article:

“Delivering on its promise to support cross-platform development, Microsoft is providing the full .NET server stack in open source, including ASP.NET, the .NET compiler, the .NET Core Runtime, Framework and Libraries, enabling developers to build with .NET across Windows, Mac or Linux. Through this implementation, Microsoft will work closely with the open source community, taking contributions for future improvements to .NET and will work through the .NET Foundation.”

There is no mention of client technologies such as WPF moving over to Linux or Mac, but that’s understandable – moving the .NET Core and server stack there is already a remarkable achievement, and whether all the other .NET technologies will follow suit in the future can only be subject to speculation at this stage.

Releases

A post on the Visual Studio blog announces new Visual Studio-related releases.

The first of these is Visual Studio 15 Preview, which supercedes the previous Visual Studio 14 CTPs:

Download Visual Studio 2015 Preview. This is the first full preview of what we used to call Visual Studio “14.” Even if you’ve been following the earlier CTPs, you’ll find some new things in here, including a new Visual Studio Emulator for Android and support for building Android applications using C++ based off of Clang and LLVM. There’s an Azure VM image available in the Gallery as well. You can get the entire list of feature and enhancement from Visual Studio 2015 Preview release notes. [UPDATE: The language packs for Visual Studio 2015 Preview are now available for download.]”

Before you rush out and try the new preview, though, check out this little warning:

“Since the majority of initial comments tend to be questions about supported configurations, I’ll put this up front: before you try to upgrade from Visual Studio “14” CTPs to Visual Studio 2015 Ultimate Preview, first uninstall Visual Studio “14” CTP – if you don’t, your system can wind up in an unstable state.”

As Somasegar explained in his Connect(); speech, the new .NET version will be known as .NET 2015, which intentionally breaks away from the previous versioning system.

Another release is Visual Studio Community 2013, which is free for commercial/non-commercial use for teams up to 5 people, “includes all the great functionality of Visual Studio Professional 2013”, and brings together the old Express editions which previously were in separate units for web development, application development, etc.

Finally, Microsoft has announced the availability of Visual Studio 2013 Update 4.

Other Enhancements

There are a myriad of enhancements throughout Visual Studio, and they are certainly not limited to the server stack or .NET becoming open source. Visual Studio is getting an emulator for Android (as already quoted above), there will be enhancements to WPF,  and lots more. Somasegar’s overview will give you an idea of what’s new, and the Visual Studio blog’s post has all the details.

Further Reading

For more information about the upcoming features in Visual Studio 2015 and .NET 2015, check out:

Bass tab – Seven Nation Army by The White Stripes

Pretty cool song (video below), which was later corrupted by Italian football fans into a completely degraded “po po po” song.

This song is in the key of C, like the others I’ve tabbed so far. The basic tune is pretty straightforward:

  • E E G E D C B

…which on a tab would read as:

G|--------------------
D|---2-25-2-----------
A|----------5-3--2----
E|--------------------

Then there is the instrumental which is basically the same as the above, but every second time it is played, there is an extra bit, which is:

  • E E G E D C D C B

Which is just:

G|-----------------------
D|---2-25-2--------------
A|----------5-3-5-3-2----
E|-----------------------

So basically, for most of the tune you play the first one. During the instrumental, you play the first one, then the second one, then the first one again, then the second one again.

On Goal-Orientedness and Mediocrity

It seems that Jessica at TodayWasMeaningful has just posted another brilliantly insightful article, “what you lose when you’re busy“. This article deals with the need to slow down and enjoy individual moments in your life rather than continuously feeling pressured to do things.

I am very familiar with this theme. I have always been goal-oriented myself. After obtaining my first degree, I could not resign myself to live merely for the work routine, so I started a Master’s degree, continued to learn programming on my own time, pursued other software projects, etc. And as the years rolled on, I found that while I was still managing to keep up with my tasks, most of the time I rushed through them, precisely because my time was so limited. The end result was that quality suffered, and that I was unable to complete any spare-time projects I wanted to do, and because of all my commitments, I did not have time to learn technology that would be useful for my career development.

It is surprisingly easy to get addicted to goal-orientedness. You know, I can actually write this article here and now because I took the morning off from work, without having planned to do anything specific this morning. Until very recently, I would never have done that. Any vacation leave I took was booked with specific goals in mind: to travel, to study, to run errands, etc.

Why is idle time such a stigma nowadays? Is it really so terrible to spend the morning listening to the waves, or watching TV, or dusting off the furniture? That same idle time is that which allows you to relax, to recollect your thoughts, and to be creative. It is not hard to imagine why there is so much pressure to do, and to achieve, nowadays. Just think of how many years it will take you to pay off your mortgage, just look at how many requirements are listed on an average software developer vacancy nowadays, look at all the things that are expected of you from your friends, your colleagues, your family, and most of all, yourself. Because although it’s really easy to get addicted to goal-orientedness, it’s also quite easy to break out of it. It’s just a switch, and it’s in your mind.

I want to clarify something here: setting goals is not a bad thing. The bad thing is biting more you can chew, attempting to be too productive without leaving any quality time to yourself; being entirely absorbed in the routine. I think Jessica’s article points this out extremely well:

“i slow down when i’m eating so i can savor the flavor, i try and walk slower so i can see all of the beauty, and i try not to rush.  i do my best to not wish my days away- to trust in the process and appreciate the steps it takes to get there.  because what i know is that i’d hate to reach the destination to find that i’d missed out on the journey.

And this is something that I think is a big problem in today’s society. Have you ever noticed how the entertainment industry (think computer games, films and music) is mostly producing unoriginal stuff using the same formulas as before, and the quality is constantly getting worse? Have you ever watched a romantic comedy or a disaster movie that actually didn’t use the standard template for its story? And that’s not just limited to the entertainment industry, as Chris Colombo’s article on academic trends illustrates:

“Ironically, the increased pressure and competitiveness on academics, has only served to lower the quality of research – researchers might be busier than ever writing project proposals and reports, supervising students and churning out papers, but the quality, the innovation, and the pioneering elements are slowly being eaten away.”

The constant pressure by large institutions to satisfy the demand is resulting in mediocre, short-sighted work, which is far within the potential of the people who do that work. In a society where money and prestige are vital to survival, and where these may be obtained more easily with mediocre work, there is little reason to stand out. This is just another form of goal-orientedness: neglecting the means to focus on the end is a complete waste of potential.

Someone very close to me used to say:

“What is worth doing, is worth doing well.”

The way I see it, if you’re going to invest a significant amount of effort to do something, then you should take the time you need to do it properly, or do nothing at all. It is better to attempt nothing at all than to waste your time and effort on something meaningless. Failing fast leaves you free to pursue whatever ideas are most appealing at any given time.

Guitar/Bass tab – Don’t Fear the Reaper by Blue Oyster Cult

This is “Don’t Fear the Reaper”, a song by Blue Oyster Cult released in 1976, which makes it close to 40 years old. Wow. There is also an Apollo 440 cover (1995) which I think is pretty decent.

The basic tune, which is in the key of C, goes:

  • A E A G
  • G B D G
  • F C D G
  • A E A G

This guitar tab is a pretty good rendition of the tune, so I’ll quote the main part below as-is (just added the string names at the left side):

     Am       G        F       G
e|-------------------------------------
B|-------------------------------------
G|-------2-0--------0--------0-------0-
D|-----2----------0--------0-------0---
A|---0----------2--------3-------2-----
E|------------3--------1-------3-------

Since only the top four strings of the guitar are used, the same tab can be used directly on bass guitar without any modifications.

Guitar Tab – Prayer in C by Lilly Wood and The Prick

If you’ve heard the Robin Schulz remix of Prayer in C by Lilly Wood and The Prick, or even the original, you’ll recognise the catchy guitar tune. As the name suggests, it’s in the key of C, and that means no sharps or flats. The tune goes something like:

  • A A B C B A E
  • E F E D
  • D E F D
  • F F G F

This could translate to the following guitar tab:

e|--5-57875--------------------
B|---------5--565----56---6-686
G|---------------7--7--7-------
D|-----------------------------
A|-----------------------------
E|-----------------------------

This is not very different from other guitar tabs for this song out there, but it has the advantage that the notes are concentrated between the 5th and 8th fret, allowing you to play the tune without ever needing to slide your left hand.

"You don't learn to walk by following rules. You learn by doing, and by falling over." — Richard Branson