Wednesday, 28 July 2010

Service Locator pattern

A pattern that is showing up frequently in .Net development at the moment is Service Locator. It has appeared in the Composite Application Library (Prism - intended for use in Silverlight and WPF applications) as well as ASP.Net MVC. Service Locator is often seen going hand in hand with DI and IoC and one useful implementation of Service Locator might be to decouple an application from specific IoC containers (i.e. use the Service Locator pattern on top of IoC).

In essence, Service Locator is a simple pattern:

“Provide a global point of access to a service without coupling users to the concrete class
that implements it.”
*
Martin Fowler describes the pattern in the following terms:
“The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need.” **

service-locator

The Composite Application Library documentation offers a number of drawbacks to Service Locator:

“The Service Locator pattern has the following liabilities:
  • There are more solution elements to manage.
  • You have to write additional code to add service references to the locator before your objects use it.
  • Your classes have an extra dependency on the service locator.
  • The source code has added complexity; this makes the source code more difficult to understand.” ***

In short the criticism is that Service Locator adds complexity to the application. Martin Fowler also notes that use of Service Locator can lead to testability issues:

“I've often heard the complaint that these kinds of service locators are a bad thing because they aren't testable because you can't substitute implementations for them. Certainly you can design them badly to get into this kind of trouble, but you don't have to.”

Common Service Locator

Many frameworks (including MVC 3) are now working to the Common Service Locator library. This is described in the following terms:
“The Common Service Locator library contains a shared interface for service location which application and framework developers can reference. The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references.”
A number of IoC frameworks already provide implementations of the core interface (IServiceLocator) including Spring.Net, Unity, and Castle Windsor. The IServiceLocator interface requires that an IoC container provide the following methods:
TService GetInstance<TService>();
object GetInstance(Type serviceType, string key);
TService GetInstance<TService>(string key);
IEnumerable<object> GetAllInstances(Type serviceType);
IEnumerable<TService> GetAllInstances<TService>();

This is interesting but one has to ask if it’s an abstraction too far.

Update: If you are considering using the Service Locator pattern you should be aware that it is regarded by many as an anti-pattern. See Service locator anti-pattern.


* Service Locator, Game Programming Patterns / Communicating Patterns
** Using a Service Locator, Martin Fowler
*** Service Locator

Friday, 23 July 2010

A reminder about boxing and unboxing in C#

Here is a quick reminder about boxing and unboxing in C#. MSDN documentation contains this concise description of boxing and unboxing:

“Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.” *

All primitive types (byte, char, int, long, etc.) and structures are value-based types derived from System.ValueType. Because value types are stored on the Stack they can be created and accessed more efficiently than reference types. Reference types are stored on the Heap and must be accessed using references.

An example of boxing and unboxing:

int i = 123;
object o = (object)i; // boxing
int j = (int)o; // unboxing

Why is this important?

Boxing and unboxing operations are computationally expensive in relation to other simple assignments (for example, when a value type is boxed, a new object must be allocated and constructed). If you have code which undertakes a lot of boxing operations you may run into performance issues.

Determining which methods and properties will cause boxing is possible by checking their their signatures. If a method takes an argument of type object or the argument is an interface then if you were to pass in a value type instance it will be boxed.

Note it is very easy to slip into boxing operations:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("Boxing: {0}, {1}", i, i + 1); // Boxing here   
}

You could get around this by calling the ToString() method early to prevent allocation on the heap:

var sb = new StringBuilder();
for(int i = 0; i < 10; i++)
{
    sb.AppendFormat("No boxing: {0}, {1}", i.ToString(), (i + 1).ToString()); // No boxing   
}

Value types and reference types

Again MSDN documentation provides a description of value types:

“Variables that are based on value types directly contain a values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.” **

There are 2 main categories of value types:

  • Structs (e.g. numeric types: integral types, floating-point types and decimal; bool; user defined structs)
  • Enumerations

In essence, value types are lightweight objects that are allocated on the current thread's stack (see Stack and heap below). There are exceptions to this (e.g. when a value type is allocated as an element of an array or is a field of a reference type). When an instance of a value-type is created a single space in memory is allocated to store the value. When instantiating a reference type an object is created in memory and is handled through a reference (somewhat like a pointer).

Stack and heap

The Stack can be thought of as being responsible for keeping track of what's executing in the code (the call stack). When a method is called (a Frame) data is pushed onto the Stack. Once the method executes the data is popped off the Stack and is discarded. Only the ‘top’ item is available in the Stack (typical behaviour for a stack being a last-in-first-out memory structure).

The Heap can be thought of as being responsible for keeping track of the objects referenced by the code. Any element in the Heap can be accessed directly.

Garbage collection

The Stack does not require garbage collection. It is self-maintaining because items are popped off the stack and discarded as they are used during program execution. On the other hand the Heap is subject to garbage collection.

* Boxing and Unboxing (C# Programming Guide)
** Value Types (C# Reference)

Friday, 23 July 2010

Sunday, 18 July 2010

Visual Studio 2010 keyboard shortcuts

Here are a bunch of keyboard shortcuts for Visual Studio 2010 that I find useful but keep forgetting.

Code completion

Ctrl + Period (.) - Expands the Smart Tag Menu (e.g. to add a ‘using’ statement).
Tab - Inserts expanded code snippet using a shortcut (for example type ‘class’ and hit Tab twice)
Ctrl + Space - Completes the current word in the completion list

Building, running and debugging

Ctrl + Shift + B - Build the solution (also try F6)
F5 - Start the application with Debugging
Ctrl + F5 - Start the application without Debugging
F9 - Sets or Removes a breakpoint at the current line

Navigation

Ctrl + ] - Moves the cursor to the matching brace in the source file
Ctrl + Hyphen (-) - Moves cursor to its previous position
Ctrl + Shift + Hyphen (-) - Moves cursor to the next browsed line of code
Shift + F7 - Switch between the Design and Source View of the document
Ctrl + Shift + F - Displays the ‘Find in Files’ tab of the ‘Find and Replace’ dialog box
Shift + F12 - Displays a list of all references for the symbol selected
Ctrl + / - Moves focus to the Find/Command box

Windows

Shift + Alt + Enter - Toggle Full Screen Mode
Ctrl + M + O - Collapses all Regions to provide a high level overview of the types and members in the source file
Ctrl + M + L - Toggles all previously collapsed Regions
Shift + Esc - Closes the current Tool Window with focus

Other shortcuts

Ctrl + Alt + L - Show Solution Explorer
Ctrl + Shift + A - Displays the Add New Item dialog box
Alt + Shift + A - Displays the Add Existing Item dialog box

Friday, 16 July 2010

Comparing the MVC, MVP and MVVM patterns

Having spent some time looking at several presentation technologies recently I thought I should take stock of a number of design patterns that are frequently referenced.

Silverlight and WPF are often associated with the Model-View-ViewModel (MVVM) pattern (see frameworks such as Prism, MVVM Light, Caliburn etc). ASP.Net MVC of course utilises Model-View-Controller. In the past I have tried to overcome some of the short-comings of ASP.Net Web Forms using variations of the Model-View-Presenter (MVP) pattern.

Each of these patterns tries to address a number of problems:

  1. Where and how do we maintain state in the UI?
  2. Where does business logic live in the application and how is it invoked?
  3. How do we keep the UI synchronised with changes to the data and between UI elements?
  4. How can we ensure good separation of concerns and create loosely coupled testable code?

So the question is, how do they compare?

Note: There are variations on the theme here so there may be alternatives especially with MVP (e.g. Passive View, Supervising Controller, Front Controller).

mvc-mvp-mvvm

MVC MVP MVVM
Input is routed to the Controller.

The Controller decides which View to render and builds the Model which is bound to the View.

A Controller can choose to render one of many Views.

The View has no knowledge of its Controller.

Business logic exists in the Controller.

MVC is useful when state can’t be maintained between user input requests (e.g. over HTTP – a stateless protocol).
Input is routed to the View.

The Presenter updates the View usually in response to events raised by the View.

State is effectively stored in the View.

Business logic exists in the Presenter.
Input is routed to the View.

The View knows about nothing but the ViewModel.

The ViewModel knows about nothing but the Model.

The View gets its data from the ViewModel, not the Model itself. This is generally accomplished by data binding. 

State and business logic exist in the ViewModel.

The ViewModel can be thought of as an abstract representation of the UI.

MVVM is useful when state can be maintained between UI requests (e.g. Silverlight, WPF).

Monday, 12 July 2010

WCF Service Reference returns array and not List<T>

If you create a Service Reference to a WCF service that has operations that return generic collections you might be surprised to find the collection is exposed on the client as an array. This is the default behaviour for a WCF Service Reference but it is configurable.

To change the collection type for operations:

  1. In Visual Studio 2010 right-click on the appropriate service reference.
  2. Choose Configure Service Reference… from the pop-up menu.
  3. Choose an appropriate Collection Type on the dialog box (see image below).
  4. Click OK.

Image1

Monday, 12 July 2010

Sunday, 11 July 2010

Screen Conductor and other patterns

Silverlight and WPF development have lead to the uptake of a number of development patterns many of which were first introduced by Martin Fowler or which are variations of them. This post contains notes about the various patterns that are appearing in frameworks like Caliburn.Micro or Prism.

These patterns are put together to form a presentation framework.

Firstly, there is the Application Controller:

“A centralized point for handling screen navigation and the flow of an application.” – http://martinfowler.com/eaaCatalog/applicationController.html (Martin Fowler)

The Application Controller is often comprised of a number of elements such as:

  • Screen(s)
  • Screen Factories
  • Screen Factory Registry
  • Screen Conductor
  • Screen Collection
  • Subject

Screen

  • The class that handles coordinates the Model, View and ViewModel.
  • Coordinates the marrying of a View to a ViewModel (the View doesn’t know about the ViewModel, the ViewModel doesn’t know about View).
  • Implements the IScreen interface.
IScreen
  • An interface that all Screens will implement.
  • Requires methods such as CanLeave() and CleanUp().

Screen Factory

  • There is a one-to-one relationship between Screen Factories and Screens.
  • Screen Factories implement the IScreenFactory interface
  • The Screen Factories are registered with the presentation framework (i.e. the Screen Factory Registry singleton class).
  • Screen Factories are used by the Screen Conductor to instantiate screens.
IScreenFactory
  • Requires a CreateScreen() method.

Screen Factory Registry

  • The Screen Factory Registry contains a registry of all of the screen factories.
  • Modules can register their Screen Factory classes with the Screen Factory Registry.
  • The Screen Factory Registry has methods including GetFactory(), HasFactory(), and a Screen Factory Dictionary

Screen Conductor

  • The Screen Conductor coordinates the creation and destruction of screens.
  • The Screen Conductor makes use of the Screen Factory Registry which it uses to create Screens as necessary.
  • Screen creation includes screen visibility, screen location, loading Subjects into screens, etc.
  • The Screen Conductor has a Screen Collection; a collection of all activated screen instances.
  • The Screen Conductor is often a singleton.

Screen Collection

  • The Screen Conductor has a Screen Collection which contains all of the activated screen instances.
  • The Screen Collection is maintained by the Screen Conductor.

Subject

  • The Subject is analogous to the Model; it’s what is required by the screen to fulfil its purpose.

 

After the Application Controller there is the Application Shell.

Application Shell

  • The Application Shell is analogous to the main form in the application.
  • The responsibility of the shell is to hold the main components of the user interface (e.g. menus, ribbons, panels, docking managers, etc.) for the screens that get activated later. 

 

There sometimes are other elements that are combined with the above as part of the Presentation Framework.

Bootstrapper

  • The Bootstrapper is responsible for instantiating elements like the Application Shell and the IoC container (should one be used).
  • The Bootstrapper can also be used to activate services used by the application (e.g. caching service).

Wednesday, 7 July 2010

What is the Windows Process Activation Service (WAS)?

Here are some brief notes on the Windows Process Activation Service.

“Windows Process Activation Service (WAS) is the new process activation mechanism for the Windows Server 2008 that is also available on Windows Vista. It retains the familiar IIS 6.0 process model (application pools and message-based process activation) and hosting features (such as rapid failure protection, health monitoring, and recycling), but it removes the dependency on HTTP from the activation architecture. IIS 7.0 uses WAS to accomplish message-based activation over HTTP. Additional WCF components also plug into WAS to provide message-based activation over the other protocols that WCF supports, such as TCP, MSMQ, and named pipes. This allows applications that use communication protocols to use the IIS features such as process recycling, rapid fail protection, and the common configuration system that were only available to HTTP-based applications.” * (my bold)

“The Windows Process Activation Service (WAS) manages the activation and lifetime of the worker processes that contain applications that host Windows Communication Foundation (WCF) services. The WAS process model generalizes the IIS 6.0 process model for the HTTP server by removing the dependency on HTTP. This allows WCF services to use both HTTP and non-HTTP protocols, such as Net.TCP, in a hosting environment that supports message-based activation and offers the ability to host a large number of applications on a given machine.” ** (my bold)

WAS allows applications to be hosted in a more robust and manageable way:

  • Applications start and stop dynamically in response to incoming work items that arrive using HTTP and non-HTTP network protocols.
  • Process recycling to maintain the health of running applications.
  • Centralized application configuration and management.
  • Applications can take advantage of the IIS process model without a full IIS installation.
  • A single WAS server instance can be home to many different applications.
  • Applications are organised into groups called sites.
    • For the purposes of addressing and management.
    • Applications are also grouped together into application pools.
      • An application pool can house many different applications from many different sites.
      • Each application pool corresponds to an instance of a worker process (w3wp.exe).
  • Within a site, applications are arranged in a hierarchical manner
    • Reflects the structure of the URIs

 

* http://msdn.microsoft.com/en-us/library/ms730158.aspx
** http://msdn.microsoft.com/en-us/library/ms734677.aspx

Wednesday, 7 July 2010