Category: WCF

Castle WCF Facility

In the previous post we saw how to provide Inversion of Control capabilities to a WCF service. That’s pretty cool but unfortunately it requires a big refactoring if you plan to apply the Dependency Inversion pattern on an existing WCF project.

Today we will see an interesting alternative provided by Castle project. If you are not aware of Castle, you can have a look at the community web site here. Castle provides a set of tools for NET, Active Record, Dynamic Proxy, Windsor and a set of facilities that you can easily plug into your code.

The demo project

Before starting to have  a look at Castle Wcf Facility we need a new WCF project and a WCF web site to host our service. The idea is to create an empty service and host it, then we will refactor the project to include Castle Windsor and WCF facility.

Let’s start by creating an IIS web site, a DNS redirect and a folder for our IIS web site. The final result will be like the following one:


Now we need to create the new project in Visual Studio. I have created a solution that contains 2 projects:

  • Empty WCF Service Library named “Service.Contracts
  • Empty WCF Service Library named “Service.Implementations
    • reference the project “Service.Contracts

And this would be the final result of this step:


We have just implemented the correct way of creating a WCF service implementation and a WCF service contract. The Client will have a reference to the contract assembly in order to be able to work with the service implementation, without the need of using a Proxy. This concept is outside the fact that I will use an ioc container, it’s just a lot easier than adding a “web service reference” in visual studio and carry tons of useless proxy classes in your project.

Hosting WCF service

The final step is to host this WCF Service inside an IIS ASP.NET or ASP.NET MVC website. I have create a new “web site application” and from the options I choose “WCF service application”. Then I select my local IIS for the development path, but this is up to you.


Now Visual Studio will ask you if you want to override the current web site or use the existing content. If you choose the second option you will have to provide also web.config configuration and initial setup, so I kindly suggest the first option.

If everything went ok you should be able to visit the default service created by Visual Studio at this url: http://staging.service.local/Service.svc.

Now we need to change the content and the name of the .svc file, but before we need to add a reference for Contracts and Implementations from the solution explorer!

We need to reference the Implementation because we don’t have a factory yet able to translate the IServiceContract into a ServiceImplementation class. So the next step is to install in our solution the WCF castle facility nuget package.


Add WCF facility

So far we didn’t need any external tool because we have an empty service created by default by Visual Studio with a dummy code, or probably during the tutorial you have already changed your service to so something more interesting. The next step is to add a facility in order to be able to change the default factory used by IIS to create an instance of our service.

The first step is to add a new global.asax file if you don’t have one already and plug the Windsor container inside the Application_Start event.
This is my global.asax file:

Now, in the code behind file we want to create an instance of a new Windsor Container during the Application_Start event:

And this is the code to initialize a new container. In this code we need to pay attention in the way we specify the server name, because WCF facility uses the service attribute value to search inside the Windsor container. So, this is the code to register the service:

And this is the change we need to apply to the Service.svc file:

Now your service is ready to use dependency injection under the power of Castle Windsor.

Add a dependency to a WCF service using Windsor

Simple example, I have a service that requires an ILogger injected in it. I need to change the code for my service to allow injection and then I need to register the logger in the global.asax file during the Windsor container activation process.

And this how we change the registration in the container:

The source code is available here:

WCF and dependency inversion using Castle Windsor

When you start to work with TDD and other Agile practices the first thing you try to apply almost everywhere in your code is the Dependency Inversion pattern because you want to invert the logic of your dependencies to make your code more testable and maintainable.

In order to accomplish this result I am using Castle Windsor, while before 2013 I was working with Microsoft Unity. I am not going to jump into the conversation “Which Inversion of Control container is better?” because it really depends on what you need to do. For years I was more than satisfied with Unity but recently I started to create complex bootstrappers for my applications and I found Windsor more flexible, that’s it! Nerd smile

How does WCF create a service instance?

First of all, in order to apply dependency inversion inside WCF we need to understand how WCF works and how it creates new service instance. I found this article on MSDN very helpful during my researches: Extending WCF.

So, this is the final result I want to obtain:


When you create a new service in WCF, you can specify the factory that will be in charge of creating the service instance.

This is the code you should use to specify the factory:

Now, the factory should start a new instance of our service, or better, should use the ioc container to resolve an instance of that service.

Second step is to create a custom host that will add a new behaviour to our service, the behaviour will call the service locator (I know it’s an anti-pattern …) to inject the dependencies. In my case, Castle Windsor.



Service behavior

So, the instance provider is able to retrieve a registration for our service using the service locator:

That’s it. Of course my container needs to know what is my service registration, and with Windsor I have two options:

And of course you need to change the markup of your .svc file depending on how you want to resolve the service, with the interface or with the  class type.

Dependency Injection

Now, let’s assume that my service needs an IUnitOfWork contract, how should we do that?

First of all we need to register both types in our container, and with Windsor one of the possible options is this one:

And my command service is constructed in this way:

Note for purist of CQRS: I know that a command service should get a command dispatcher injected but for this blog post I guess it would not make things clear enough, so a unit of work or an IRepository would make more sense.

TDD a WCF service, is it possible?

Right now I am working on a CQRS project, and I am using WCF as my web service technology. In this project I decided to challenge myself and make a full TDD project. The first big problem I found was to simulate a real web server, because I didn’t want to hit a production or QA environment to run my tests.
Second I didn’t want to write any integration test at all, so I had to figure out how to create an in-Process test to run my WCF methods.

Why in-process test? When you write a unit test, you should test a single functionality, and in order to make the test atomic, it should run in-process. It should not involve third party tiers like a database or IIS, otherwise the test won’t be in-process anymore, so it will became an Integration test.

The first idea I came out was to fake the behaviour of IIS, and in order to accomplish this I could easily work with a mock framework like Typemock and mock out the entire IIS infrastructure.

Is this what I really want? Not at all. I don’t want and I don’t need to fake the behaviour of IIS, I need an instance of it because my WCF services are using custom factories and custom behaviours and I need to be sure they are acting in the right way.

So I have created two different type of tests. The first one is pure Unit Test, where I verify the command behaviours:

The second one is the (in)famous integration test, where you call the WCF service and test the overall process. Unfortunately for the second step I couldn’t find anything really TDD so I had to figure out by myself a different solution.

IIS Express

Yesterday I spent some time googling around for a solution while I found a nice post from Scott Gu about IIS express. With IIS express we have an in-process IIS server that we can startup or shutdown at any time during the lifecycle of our tests. It provides almost all the functionalities provided by IIS and it also trigger the Application_Start event, something not very well handled by Cassini …

So, first of all I had to figure out how to bootstrap my unit tests to run over a different IIS than the one configured in the web.config.

Piece of cake, first of all I need something that allows me to bootstrap IIS express before my unit test harness starts:

Then I need another utility to kill everything when my test harness is done:

At this point I can write any test in the following format:

I found this technique very useful because we work with TFS on Azure so my Build environment cannot be polluted at all with any third party components or by installing the WCF service under test in the build machine.

In the same way I found very quick to bootstrap IIS express for my tests, honestly they are faster than running on my local IIS 8.

IIS Express utility class

Below is the code I use to initialize IIS express, feel free to use it in your tests and let me know if you come up with a better solution than this one.


Build enterprise applications with WPF, WCF, EF and Prism. Tutorial 09.

Today we will see the modularity concept of Prism. Probably the best part of it, as it will allow us to build a real plug-and-play application where the main Shell won’t know anything about the modules.

Discover and load the module.

What does it mean? As we saw in the previous article, we have declared a reference in our Shell for the hello world module. In this way we force the Shell to be compiled including in the shell project a reference to the Hello World module. Fine, but what happen if we want to replace this module with a new version? We need to change the reference in the project and recompile it … Pretty ugly for a modular application doesn’t it?

The basic concept in Prism is that we can discover on fly the available modules and load them … This is the workflow process of discovering and loading a module in Prism.

 prism module

There are different ways to load a module. As we saw in the previous article, the easiest way is to add a direct reference to the module in the Shell and load it in the bootstrapper:

The second way is to add the module reference in the app.config and REMOVE the code in the bootstrapper. In this way we won’t need to recompile the module each time we will run the application in Visual Studio and we won’t need a direct reference to it. Let’s see the code below. I have a added an app.config file in my shell project:

I am using the composite section in the app.config file to load a specific module. Now, in order to make this ‘runnable’ we need to:

  • remove the reference in the Shell project
  • clean-up the code in the bootstrapper that loads the module

The shell project will use this code now to load the Module catalog:

As you can see we are telling to Prism to look in the app.config and load the modules available there. In order to make the module available in the modules folder inside the bin folder of the shell you can play with MSBuild or a post-event action in VS. I copied this code from MSDN and added to the post event build action in the HelloWorldModule project properties:

Pretty cool! We can now work with our modules without breaking any change in the Shell project, and trust me, when you work on a team, this happens every day …

Additional configuration options.

Of course the game is not done yet. We have a lot of options that we can configure in the app config in order to load modules on fly and to add dependencies from other modules. For example, let’s say that Outlook can’t open a view if the ribbon is not loaded, but the ribbon is on another module … Wink

Load on demand

We can specify, for example, that we want to load on demand (by request) a specific module that we don’t know. Pretty cool as this is how should work a real modular application. In order to do this we don’t need anything more that this tag in the app.config:

Now that we setup the module to load “onDemand” the module won’t be load in memory until we will instruct Prism to do that. This is a real plug and play concept, because without any dependencies we can load on demand part of our UI during the program execution. In Windows Form this can’t simply be done!

There you go, in a simple call from any view we can ask for a specific module. The initialize method of the module will be call and our UI will receive the ‘default’ view of that module, injected in the shell or in another module … there are no limitations at all.

Now we are ready to build the first cool module of our app, the main Ribbon bar.


Build enterprise application with WPF, WCF, Prism and Entity Framework. Tutorial 08.

Update: source code and documentation are now available on CodePlex at this address:

Today we will build the skeleton of our application using the latest version of Prism, available in this section of MSDN: Prism February 2009. One of the reasons that I didn’t write anything concrete until now is the fact that I knew that the new version of Prism was coming this month. Smile

The classic Hello World application.

As for every tutorial, is always better to start with the classic Hello World in order to understand, step by step, how Prism structures the various part of the UI.

Let’s open our VS Solution (remember that if you download the solution from my CodePlex repository the solution will contains already the entire code of each article) and let’s add a new project of type WPF application. I called Prism.Shell because this one will be our shell that will contain the bootstrapper.

Note about references.

In order to add the assemblies that I will mention in this and in the next tutorials you must download the latest version of Prism V2 and build the solutions so you will have all the assemblies you need. This is the structure of my Prism Framework:


For practice I have already compiled all the required assemblies and added them to a solution folder in VS. This is what I have and what I reference in my projects:


Finally, remember also that you can open each Prism component and re-compile it, add new future and suggest new capabilities to the Microsoft team. They will appreciate for sure! Smile

So … coming back to our project this is what we need in our Shell:


  1. Microsoft.Composite
    This is the core of the composite framework
  2. Microsoft.Composite.Presentation
    This assembly contains the components that target Prism for WPF
  3. Microsoft.Composite.UnityExtension
    It’s a utility assembly for unity IoC container

The Shell XAML container.

Let’s add a new Windows Component from WPF template and the name will be Shell.xaml. Below the code I have added to the window in order to show 3 different regions.

1: <Window x:Class=“Shell.Shell”

2: xmlns=“”

3: xmlns:x=“”

4: Title=“Hello World with Regions” Height=“500” Width=“500”>

5: <DockPanel>

6: <ItemsControl x:Name=“HeaderRegion” DockPanel.Dock=“Top” Height=“50”>


8: </ItemsControl>

9: <ItemsControl x:Name=“LeftRegion” Width=“100” DockPanel.Dock=“Left”>


11: </ItemsControl>

12: <ItemsControl x:Name=“MainRegion” DockPanel.Dock=“Bottom”>


14: </ItemsControl>

15: </DockPanel>

16: </Window>

We have added 3 ItemsControl inside a DockPanel in order to design a simple Outlook style layout with an header, a main container and a left navigation menu.

Now we need to extend this control using the attached properties in order to use the Prism region adapters. This is the code we must include in the xaml declaration:

1: xmlns:cal=””

Now we are ready to change our xaml code in this way:

1: <ItemsControl

2: x:Name=“HeaderRegion”

3: cal:RegionManager.RegionName=“HeaderRegion”

4: …

5: <ItemsControl

6: x:Name=“LeftRegion”

7: cal:RegionManager.RegionName=“LeftRegion”

8: …

9: <ItemsControl

10: x:Name=“MainRegion”

11: cal:RegionManager.RegionName=“MainRegion”

12: …

We said to Prism: “Hey when you load the Shell assign to each ItemsControl the corresponding Region using the attached property regionManager.RegionName”.

The bootstrapper.

The bootstrapper is nothing more than the entry point of our application. He is in charge to resolve and charge the modules and assign them to the corresponding view for the initial setup. So we need to create a new class in our Shell project and call it Bootstrapper.cs. This is the code we need for our initial setup:

1: protected override IModuleCatalog GetModuleCatalog() {

2: ModuleCatalog catalog = new ModuleCatalog();

3: return catalog;

4: }

This method should return an instance of the modules catalog used inside the application. What is the module catalog? The catalog contains all the modules we will use in our application. As we don’t have any module right now, this method returns an empty catalog. We will see in the future that we can load modules in the catalog also during the application execution.

1: protected override DependencyObject CreateShell() {

2: Shell shell = new Shell();

3: shell.Show();

4: return shell;

5: }

The create shell method, is only creating a new instance of the main window, called Shell and showing it to the user. Let’s say that this is the first entry point.

Now we need to modify the app.xaml in order to startup our application using the Boostrapper. First of all remove this row from the xaml code:

1: StartupUri=”Window1.xaml“>

We don’t want anymore that the application will start using this window but we want to use the boostrapper.

Now we need to modify the app.xaml.cs in this way:

1: protected override void OnStartup(StartupEventArgs e) {

2: base.OnStartup(e);

3: Bootstrapper bootstrapper = new Bootstrapper();

4: bootstrapper.Run();

5: }

As you can see, starting from now our application will request to the bootstrapper to load the first window and we won’t have any more dependency to the related main window.

You should be able to press F5 and run this part of the tutorial without any problem.

Add custom content to the regions.

Until now we wrote the code to startup our prism application but we still need to create at least 3 views, in order to load some content to the corresponding regions.

We need for this a new “module” that in VS is nothing more than a Class Library Project. We need the following references in order to be able to use WPF and the composite framework in our assembly:


The first thing that every module will have is a “module class” that will implement the IModule contract from the composite framework. It’s pretty easy because this contract exposes only 1 method “void Initialize()”. The basic structure of the module class is something like this:

1: public sealed class HelloWorldModule : IModule {


3: private readonly IRegionManager regionManager;


5: public void Initialize() {


7: }


9: public HelloWorldModule(IRegionManager regionManager) {

10: this.regionManager = regionManager;

11: }

12: }


So we have declared a private IRegionManager that will represent the main region manager instantiated by the bootstrapper. As soon as the bootstrapper will load it will inject the region manager inside our module. Than we have created a constructor with dependency injection, this mean that as soon as the module will be declared it will receive a specific RegionManager class. Finally we have implemented the IRegionManager Initialize() method that will be used to register the views to the corresponding regions.

Now let’s go back to the shell application. We need now to add a “project reference” to the new module we have created. After that we need to add this line of code inside the Bootstrapper class:

1: protected override IModuleCatalog GetModuleCatalog() {

2: ModuleCatalog catalog = new ModuleCatalog()

3: .AddModule(typeof(HelloWorldModule.HelloWorldModule));

4: return catalog;

5: }

We said to the boostrapper that as soon as it will load it will need to add to the module catalog a new module, our HelloWorldModule class. If we try to run the app now it will run successfully but nothing will change in the UI because we still need to create the views.

What I want to show is the power of loading different views in different regions, so for this reason I am rendering a special textblock with some fancy shadows. This is the code and the final result:


1: <Border

2: Margin=“20”

3: Padding=“10”

4: BorderThickness=“3”

5: CornerRadius=“15”

6: Background=“White”

7: BorderBrush=“SteelBlue”>

8: <Border.Effect>

9: <DropShadowEffect Color=“Gray”/>

10: </Border.Effect>

11: </Border>

12: <Border

13: Margin=“20”

14: Padding=“10”

15: BorderThickness=“3”

16: CornerRadius=“15”>

17: <TextBlock

18: Text=“A custom header.”

19: FontSize=“24”

20: TextWrapping=“Wrap”

21: Foreground=“DarkSlateBlue”

22: HorizontalAlignment=“Center”

23: VerticalAlignment=“Center”/>

24: </Border>

Now, we need to add to our module 3 views using this effect in order to have this final result in our project:


Now, in the module class we need to tell to Prism where each view should be loaded in the shell region manager. The ‘declarative way’ do to that it’s pretty simple:

1: public void Initialize() {

2: regionManager

3: .RegisterViewWithRegion(“HeaderRegion“, typeof(Views.HeaderView));

4: regionManager

5: .RegisterViewWithRegion(“LeftRegion“, typeof(Views.LeftView));

6: regionManager

7: .RegisterViewWithRegion(“MainRegion“, typeof(Views.MainView));

8: }

So for each view I assign the view to a corresponding region. The region name is the one we used in the attached property of the ItemsControl in the shell view.

Now if you press F5 this will be your final result:



This is the ‘primordial’ way to use Prism and to load 3 different views in 3 different regions. The next time we will see how many way Prism offers to load a module and the corresponding view, dynamically.

Tags: WPF Prism Composite application

Build enterprise application with WPF, Prism and WCF. Tutorial 07.

Update: source code and documentation are now available on CodePlex at this address:

Design of a Rich Interface using WPF.

WPF is a very powerful language and allows you to do everything you want. The only problem is that Microsoft didn’t release yet a rich toolkit with all the controls we need and the XAML is not easy to learn.

Before starting to build a UI, usually, I follow these 3 fundamental steps.

1. Main layout of my application (MDI, Tab, Ribbon …)

2. Style of my application (Custom, Office style, Vista style)

3. Resources available for free (Icons, themes, controls)

After I have everything in my hands I can start to design the UI and match all the pieces of the puzzle. For example I can build the main environment (shell) and then create the single components (search control, navigation bar and so on).

Sketch the UI with Microsoft Blend.

At this address, you can find an evaluation version of Microsoft Blend, a nice product for WPF designer that fully integrates with Visual Studio 2008/2010. Inside this amazing product, there a tool called Sketchflow designer. You saw this tool in action in my previous post or at the MIX09.

Why we should use a sketchflow designer instead of designing directly the UI? Because when you build an enterprise application that will be used by  hundreds of users, it’s fundamental to reflect the UI to what the users want. If they already know the Office 2007 UI and the ribbon concept, it won’t be difficult for them to move inside your new WPF application. If they work with a MDI application, you will need to think about it and redesign your idea of RIA. Remember that the user is the person that will use, buy, advertise you product. It’s the most important part of your software development process. So try to satisfy it before your ego … Wink

Anyway, I will leave you the pleasure of discovering the Sketchflow world. Here I just want to show you how our application will be designed and why.
First of all the application will be divided in 3 main regions: the ribbon, the navigation and the content region. Like outlook 2007.

The layout will be something like this one:

 New Picture (15)

As you can see, we will have 3 principal regions, plus a couple of additional components, like a status bar and a search context bar.

 New Picture (15)

Get the controls you need for free.

Before buying thousands of dollars of UI controls, I usually step into Codeplex or Codeproject and I search what I am looking for. If I don’t find anything, well I start to consider to use a different approach … Smile
You will wondering why I don’t use something cool like Telerick, for example. What I don’t like about the third party controls, especially when you pay them, is the fact that you don’t give you access to the source code, and you have to pay thousands of dollars for a datagrid. Also XAML is so powerful that after you will handle it, you won’t need any third party control. Trust me!

Anyway, this is the list of controls that we will need for our application:

1. A Ribbon

2. An Outlook style navigation bar

3. A tabbed “MDI” container.

About the ribbon, finally Microsoft has released a full license to use and work with the Microsoft Office 2007 Ribbon using XAML. In order to use it you must sign and agree to the license at this address: Codeplex Office 2007 WPF Ribbon project.

About the Outlook navigation bar there are 2 good choices for free. The first one is the article on CodeProject that explains you, in a step by step tutorial, how to build an outlook 2007 navigation bar starting with a tabbed control. Very cool.

If you are lazy, there is also this set of free controls, that I use, available on CodePlex. Composite Application Contribution. Very well done and useful if you plan to work with Prism.

Then we need a Tabbed MDI container. We have already one in WPF that we can try to customize, and this is what we will do in the next articles. Otherwise you can use the one provided in the Composite WPF Contribution or there is this good article that explains how to fully customize a tabbed control.

Then we can also have the need of using a grid, right? Well if you really think you need one, you can use the XCeed data grid, for free, otherwise you can move to the WPF control toolkit or the WPF contribution, two nice open source projects that deliver some nice and useful controls.

Ready to go?

Now, from the next article we will start to build our application’s skeleton, so let’s try to be ready with everything you’ll need.

Download all these controls and add a reference into your Visual Studio Toolbox. Then agree and download the Office 2007 Ribbon project for WPF. Download the latest version of Prism and install also the Enterprise Library 4.1, required to use Prism.

Also, if you have time, try to have a look at this series of articles and web cast about WPF fundamentals. In this way you will better understand my steps.

Enjoy this tutorial and stay tuned for the next one!

Tags: WCF Prism WPF Composite application

Book Review: Architecting application for the enterprise.

Good morning everybody, first of all I want to apologize for my absence in December. I am really sorry but I was ‘trying’ to deliver a component in my office and I was so busy and tired that I didn’t have time for the blog.

Let’s start this ‘holiday’ posts with an interesting review of a software architecture book written by two friends of mine: Andrea Salatarello and Dino Esposito.


The title is: Microsoft .NET: Architecting Applications for the Enterprise (PRO-Developer) (Paperback) available at for 29.69 USD.

Chapters and sections.

The book is divided in 2 main sections: Principles and Design of the system.
The principles section talks about the architect and the architectures in software development. The design of the system talks about how the application should be architected and developed.

The first part has these chapters:

  • Architects and architecture today
  • UML essentials
  • Design principles and patterns

And the second one has the following:

  • The business layer
  • The service layer
  • The Data access layer
  • The presentation layer

Description and overall.

This is the description provided on the back of the book and I completely agree with it.

“Make the right architectural decision up front – and improve the quality and reliability of your results. … you will learn how to apply the patterns and the techniques that help control project complexity …”

I am 100% satisfy of this book as I already use these patterns and approaches  explained in depth in the book.

It’s a must to have for senior developers and software architects. You can’t miss it!!
First of all, this is the first book I have read where is explained in depth what is a Software Architect and why his role it’s fundamental in the development of a complex application. Second, it explains in depth the different approaches you may use for the various layer of an application, starting from the DBMS ending with the UI.

I wish any developer that works or will work with me, will read this book as it gives you a complete overview on how an application should be developed and when a particular layer should or should not be used.

There is also a complete open source project (NSK) on codeplex where you can see all the patterns and methodologies explained in this book. Of course, opening the Visual Studio solution and try to understand everything is not easy as it is using this awesome book.

I am really satisfy and happy! Thanks Andrea and Dino for your effort!


Build enterprise application with WPF, WCF, Entity Framework and Prism. Tutorial 06.

Configure your Customer lookup and run it on IIS 7.0

In the previous article we saw how to use WCF (a basic approach) and what we should keep in consideration if we want to use SOA as our repository.

Now we need to:

  1. Change the WCF service to point to a real database
  2. Test the service
  3. Build a web site to host our service
  4. Host the web site on IIS 7.0
  5. The the final result

Change the Customer service to reflect our database.

First of all let’s open the ServiceLibrary project and change the ICustomerService interface to reflect this:

For our menu we need two methods. The first one will retrieve all the available customers, in alphabetical order; the second one will filter this results, in order to show us only the customers that match our search criteria.

The concrete implementation of this contract will consequently change in this way:

Of course, in order to declare our Repository we need to add a reference to the DataLayer project in our WCF service. We need also to reference the entity framework .dll “” and we need also to add the connectionString section in the app.config of our WCF service, otherwise when we will instantiate a new database session (new ADVConnection()) the Visual Studio will throw an error “configuration not found … ”. This happens because the WCF is the final layers so you can use in .NET just one config file in the final layer (UI).

Now, what we want to do, is to populate the list of customer, in our service library, with the customers available in the database. Because our service is a singleton, we will do that when the first user will call the service: