Tuesday, December 30, 2008

Unity Application Block 1.2 for Silverlight - December 2008

Not many changes here for Silverlight, just adjustments to the packaging to allow it to run in Silverlight...

Unity Application Block 1.2 for Silverlight - December 2008

And -- not sure how I missed it, but Unity 1.2 was released in October.

Ah, I remember, I was on vacation...

Friday, December 19, 2008

LINQ to SQL - Dead or alive?

Microsoft claims that LINQ to SQL is not a dead technology, despite their focus on Entity Framework. From Redmond Developer News:

Tim Mallalieu, the program manager for both LINQ to SQL and the Entity Framework, ... says Microsoft anticipated the backlash but said both data access interfaces will be better off for this move. For those who don't think the Entity Framework is a suitable replacement, Mallalieu said stay tuned.

"There's some pretty nifty stuff we're doing in the beta 2 time frame that we are not speaking about as yet, I think it will give you a better experience and will reduce the anxiety that people have around the Entity Framework," Mallalieu said. "In terms of capabilities, I think will make the overall integrated experience of ASP.NET, Dynamic Data, MVC and these other things easier, we did a little bit of triaging and feedback, there is some valid feedback around complexity in the Entity Framework and we are doing things to address that. "

Especially in light of the fact that LINQ to SQL is specific to SQL Server, I think it's best to wait a while to see what happens with Entity Framework. Note that there are quite a few folks who aren't happy with the way it has turned out so far.

Wednesday, October 8, 2008

Unity 1.2 and Interception

Unity 1.2 is under development, but we do know that it will support Interception.

David Hayden has a nice screencast showing how it works.

David shows how you can add an interceptor to time the execution of a method in an object that Unity has created for you. Cool stuff. Check it out!

Monday, October 6, 2008

Fun with C# 3.0 (#4) - Nullable types and the ?? operator

C# has reference types and value types. Reference types are commonly called objects, and variables that are declared to be of a reference type can refer to an object or be null. Value types (int or bool, for example) can be stored in variables that contain the actual value, and therefore can never be null.

Sometimes it is useful to have a value type that can have a null value, so this feature has been added to C# 3.0.

This feature is implemented using generics and the type System.Nullable<T>, the shorthand for which is T?. The property HasValue can be used to see if the variable is null. Here's an example:

int? x = 10;
if (x.HasValue)
{
System.Console.WriteLine(x.Value);
}
else
{
System.Console.WriteLine("Undefined");
}

A nullable type can not be assigned to a value type. The following will not compile:


int? x = 10;
int y;
y = x;

Rather use the Value property:


int? x = 10;
int y;
y = x.Value;

Accessing Value will throw an InvalidOperationException if the nullable type is null. Use the ?? to assign a default value.


int? x = null;
int y;
y = x ?? 0;

This is equivalent to:


y = x.HasValue ? x.Value : 0;

Usage of the ?? operator is not limited to Nullable types. For example:


string name = enteredName ?? "Name not entered.";

Friday, October 3, 2008

The Common Service Locator

I have argued against making 'hard' references to an underlying Dependency Injection (or IoC) container; rather, allow the container to do the work for you, namely, inject the dependencies. I realize that it can be difficult in practice, and apparently so have others.

A group of DI container authors have come together to define a common interface for using the underlying containers without creating a hard reference to a particular implementation. This is useful when you are writing code that needs to use a container to resolve a dependency (i.e. get an instance) but you don't know or care what container is being used.

So now we have the Common Service Locator library. Thanks to Ayende for blogging it. UPDATE: Also Glenn Block.

Each container needs an adapter to implement the interface and do the translation from the common method calls to the native container calls. This allows all container references to be declared as Microsoft.Practices.ServiceLocation.IServiceLocator.

Your code has two ways of getting the container:

  • The IServiceLocater reference can be supplied by the calling code and you just use it, or
  • You code can use a static property, ServiceLocator.Current.

Here is the interface that you will use (API Reference):

using System;
using System.Collections.Generic;

namespace Microsoft.Practices.ServiceLocation
{
// Summary:
// The generic Service Locator interface. This interface is used to retrieve
// services (instances identified by type and optional name) from a container.
public interface IServiceLocator : IServiceProvider
{
// Summary:
// Get all instances of the given TService currently registered in the container.
//
// Type parameters:
// TService:
// Type of object requested.
//
// Returns:
// A sequence of instances of the requested TService.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is are errors resolving the service instance.
IEnumerable<TService> GetAllInstances<TService>();
//
// Summary:
// Get all instances of the given serviceType currently registered in the container.
//
// Parameters:
// serviceType:
// Type of object requested.
//
// Returns:
// A sequence of instances of the requested serviceType.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is are errors resolving the service instance.
IEnumerable<object> GetAllInstances(Type serviceType);
//
// Summary:
// Get an instance of the given TService.
//
// Type parameters:
// TService:
// Type of object requested.
//
// Returns:
// The requested service instance.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is are errors resolving the service instance.
TService GetInstance<TService>();
//
// Summary:
// Get an instance of the given named TService.
//
// Parameters:
// key:
// Name the object was registered with.
//
// Type parameters:
// TService:
// Type of object requested.
//
// Returns:
// The requested service instance.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is are errors resolving the service instance.
TService GetInstance<TService>(string key);
//
// Summary:
// Get an instance of the given serviceType.
//
// Parameters:
// serviceType:
// Type of object requested.
//
// Returns:
// The requested service instance.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is an error resolving the service instance.
object GetInstance(Type serviceType);
//
// Summary:
// Get an instance of the given named serviceType.
//
// Parameters:
// serviceType:
// Type of object requested.
//
// key:
// Name the object was registered with.
//
// Returns:
// The requested service instance.
//
// Exceptions:
// Microsoft.Practices.ServiceLocation.ActivationException:
// if there is an error resolving the service instance.
object GetInstance(Type serviceType, string key);
}
}



Here are the containers that have adapters at the moment:





I recommend IServiceLocator be used in all components that might need a reference to a container. Note that they are no common calls for configuring the container because this is a container-specific task that should be handled in the calling code.

Thursday, October 2, 2008

Microsoft "Dublin" addresses composite SOA applications

Microsoft just released a white paper outlining how .NET Framework 4.0 and new Windows Server capabilities (code-named Dublin) will help developers design, build and maintain Composite Applications. The white paper is available here.

What are composite SOA applications? Applications that are composed by assembling and integrating reusable services. This makes the deployment and management of applications (and servers) more complex and creates new requirements to address scalability, performance and reliability.

Microsoft has announced .NET Framework 4.0 to add functionality to WCF and WF, and also "Dublin", an add-on to Windows Server 2008, that will make SOA applications and servers easier to deploy, configure, manage and scale. The first preview will be available at the PDC at the end of October.

See the chart below from the white paper:

 

Windows Communication Foundation 4.0

Windows Workflow
Foundation 4.0

Windows Server
"Dublin" technologies

RESTful enhancements

·   Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF

·   WCF REST Starter Kit to be released on Codeplex to get early feedback

Messaging enhancements

·   Transports - UDP, MQ, Local in-process

·   Protocols - SOAP over UDP, WS-Discovery, WS-BusinessActivity, WS-I BP 1.2

·   Duplex durable messaging

Correlation enhancements

·   Content and context driven, One-way support

Declarative Workflow Services

·   Seamless integration between WF and WCF and unified XAML model

·   Build entire application in XAML, from presentation to data to services to workflow

 

Significant improvements in performance and scalability

·   Ten-fold improvement in performance

New workflow flow-control models and pre-built activities

·   Flowcharts, rules

·   Expanded built-in activities – PowerShell, database, messaging, etc.

Enhancements in workflow modeling

·   Persistence control, transaction flow, compensation support, data binding and scoping

·   Rules composable and seamlessly integrated with workflow engine

Updated visual designer

·   Easier to use by end-users

·   Easier to rehost by ISVs

·   Ability to debug XAML

Provide standard host for WF and WCF applications   

Pre-built developer services

·   Message-based correlation

·   Message forwarding service

·   Content-based message routing

·   Compensation service for long-running transactions

Greater scalability and easier manageability

·   Enable scale-out of stateful workflow applications

·   Persisting and rehydrating state for high scalability

·   Enhanced management and monitoring functions

·   Tracking store for workflow events

Supports “Oslo” modeling platform

 

 

Key takeaways:

  • Microsoft will make it easier to design applications as WF workflows that are easily integrated into WCF services.
  • WCF and WF both use XAML. Microsoft will move to a "unified" XAML to make the integration easier.
  • Microsoft is moving more toward REST for web services due to its simplicity. The REST Starter Kit will be available on Codeplex in the near future.
  • The server infrastructure (Dublin) to host and manage these new types of applications will become available after .NET 4 and Visual Studio 2010 ship.

Links:

Monday, September 29, 2008

Visual Studio 2010/.NET 4.0 Roundup

Today Microsoft announced that, although recently referred to as Visual Studio 10 or "Hawaii", the official name of the next release will be Visual Studio 2010 and it will be accompanied by .NET Framework 4.0.

eWeek reports:

Microsoft announces Visual Studio 2010 and .NET Framework 4.0, and says the overall development strategy revolves around five pillars. The first pillar involves the Visual Studio Team System (VSTS) 2010, formerly codenamed “Rosario.”

Microsoft has announced the name of the next version of its developer tools and platform: Visual Studio 2010 and the .NET Framework 4.0.

In the announcement on Sept. 29, Microsoft also described the next release through the following five focus areas: riding the next-generation platform wave, inspiring developer delight, powering breakthrough departmental applications, enabling emerging trends such as cloud computing, and democratizing ALM (application life-cycle management), said Dave Mendlen, a director of product management in Microsoft’s Developer Division.

However, Mendlen did not give an actual date for when the new technology would become available, except to say that its name implies something about the time frame of its availability.

http://www.eweek.com/c/a/Application-Development/Microsoft-Announces-Visual-Studio-2010-and-NET-Framework-40/

From InformationWeek:

In Visual Studio 2010, Microsoft also will introduce a feature it likens to an airplane's black box. While running a test of an application, a "black box" records the state of the machine and the application. That way, a tester can look at a debug log running alongside a video replay of the application that was under test and dive into all layers of the computing stack to see where a bug might have occurred.

Visual Studio Team System 2010 will include some pieces of Microsoft's "Oslo" modeling strategy, as first demonstrated at Microsoft's TechEd conference earlier this year. The Architecture Explorer will allow architects and developers to build, customize, and see an architectural diagram of an application and enforce architectural consistency on builds of a piece of software. The software will support the Object Management Group's Unified Modeling Language and domain-specific languages.

 

More screenshots from Martin Heller at InfoWorld (click to enlarge):

 

 

More links:

Videos from Microsoft.

Mary-Jo Foley's blog

SD Times

Silverlight 2 Release Candidate Now Available

Scott Guthrie announces.

There are some breaking changes between Beta2 and this RC, and we want to make sure that existing sites can update to the final release quickly once the final release is out.  As such, you can only use the RC for development right now - you can't go live with the new APIs until the final release is shipped (which will be soon though).

You can download today's Silverlight Release Candidate and accompanying VS and Blend support for it here.  Note that Expression Blend support for Silverlight 2 is now provided using Blend 2.0 SP1.  You will need to install Blend 2.0 before applying the SP1 service pack that adds Silverlight 2 support.  If you don't already have Blend 2.0 installed you can download a free trial of it here.

The final release of Silverlight is not that far off now.  It has been a pretty amazing project that has come a long way in a pretty short amount of time.

Thursday, September 11, 2008

Visual Studio 2008 SP1 Preparation Tool

Microsoft has released a tool that will prepare your system for VS 2008 SP1. It's important to run it if you have installed any beta Visual Studio 2008 software since it went RTM.

http://www.microsoft.com/downloads/details.aspx?FamilyId=A494B0E0-EB07-4FF1-A21C-A4663E456D9D 

The following pre-release programs and updates will prevent Visual Studio 2008 SP1 from installing successfully, so they must be removed prior to installation:


To remove these programs, it is recommended that you run the automated Visual Studio 2008 Service Pack Preparation Tool. This tool will remove the specified updates and programs from your system and restore the integrity of any Visual Studio 2008 features that may have been compromised during manual removal of the Visual Studio 2008 SP1 Beta release.

Monday, August 25, 2008

Tuesday, August 12, 2008

SQL Server 2008 released

Microsoft has released SQL Server 2008.

Evaluation download available here.

Hardware and Software requirements are here.

Note that if you have Visual Studio 2008 installed, you will need to upgrade to Visual Studio 2008 SP1 before installing SQL Server 2008.

Web Services Security Guide for WCF

Microsoft Patterns and Practices has released the WCF security guide.

Parts

Part I, "Security Fundamentals for Web Services"
Part II, "Fundamentals of WCF Security"
Part III, "Intranet Application Scenarios"
Part IV, "Internet Application Scenarios"

Monday, August 11, 2008

Visual Studio 2008 Service Pack 1 available

VS 2008 SP1 is now available for download with the .NET 3.5 SP1 framework.

More info here.

Visual Studio 2008 SP1 delivers:

  • Improved WPF designers
  • SQL Server 2008 support
  • ADO.NET Entity Designer
  • Visual Basic and Visual C++ components and tools (including an MFC-based Office 2007 style ‘Ribbon’)
  • Visual Studio Team System Team Foundation Server (TFS) addresses customer feedback on version control usability and performance, email integration with work item tracking and full support for hosting on SQL Server 2008
  • Richer JavaScript support, enhanced AJAX and data tools, and Web site deployment improvements

The .NET Framework 3.5 SP1 delivers:

  • Performance increases between 20-45% for WPF-based applications – without having to change any code
  • WCF improvements that give developers more control over the way they access data and services
  • Streamlined installation experience for client applications
  • Improvements in the area of data platform, such as the ADO.NET Entity Framework, ADO.NET Data Services and support for SQL Server 2008’s new features.

Saturday, July 12, 2008

Ninject revisited

In a previous post, I looked at Ninject, and based on a cursory look at the documentation, dismissed it as requiring me to decorate my component classes with attributes in order to use multi-parameter constructor injection. Thanks to a comment by ninject's author, Nate Kohari, I found that with a slight configuration change, we can duplicate the behavior of Unity.

The proof's in the pudding. Let's see if we can wire up the same components with both Unity and Ninject without having to make any changes to our component classes.

Here are some interfaces:

public interface IDataService
{
}

public interface ISecurityService
{
}

public interface ILogger
{
}


And here are some components that use them. The Business Logic requires all three, the Security service needs a DataService and Logger, and the DataService needs a Logger.



public class BusinessLogic
{
protected IDataService DataService { set; get; }
protected ILogger Logger { set; get; }
protected ISecurityService SecurityService { set; get; }

public BusinessLogic()
{
}

public BusinessLogic(ILogger logger, IDataService dataService, ISecurityService securityService)
:this()
{
this.Logger = logger;
this.DataService = dataService;
this.SecurityService = securityService;
}


public override string ToString()
{
return base.ToString() + '\n' +
Logger.ToString() + '\n' +
DataService.ToString() + '\n' +
SecurityService.ToString() + '\n'
;
}
}


public class DataService : IDataService
{
protected ILogger Logger { set; get; }

public DataService()
{
}

public DataService(ILogger logger)
:this()
{
this.Logger = logger;
}
}

public class SecurityService : ISecurityService
{

protected IDataService DataService { set; get; }
protected ILogger Logger { set; get; }

public SecurityService()
{
}

public SecurityService(ILogger logger, IDataService dataService)
: this()
{
this.Logger = logger;
this.DataService = dataService;
}
}

public class Logger : ILogger
{
}


If we don't want to use an auto-wring container, we need to know all the dependecies and create the Business object like so:



static BusinessLogic NormalWay()
{
var logger = new Logger();
var dataService = new DataService(logger);
var securityService = new SecurityService(logger, dataService);
var bizLogic = new BusinessLogic(logger, dataService, securityService);
return bizLogic;
}



How do we configure and create a BusinessLogic object with Unity? Like so:



static BusinessLogic UnityWay(UnityContainer container)
{
UnityContainer container = new UnityContainer();
container
.RegisterType<ILogger, Logger>()
.RegisterType<IDataService, DataService>()
.RegisterType<ISecurityService, SecurityService>()
;
var bizLogic = container.Resolve<BusinessLogic>();
return bizLogic;
}
}


Likewise, we can create a method to create a BusinessLogic object using Ninject, all auto-wired are ready to go. This however, requires a configuration class (MyModule):



static BusinessLogic NinjectWay()
{
var kernel = new StandardKernel(new MyModule(), new AutoWiringModule());
var bizLogic = kernel.Get<BusinessLogic>();
return bizLogic;

}
private class MyModule : StandardModule
{
public override void Load()
{
Bind<ILogger>().To<Logger>();
Bind<IDataService>().To<DataService>();
Bind<ISecurityService>().To<SecurityService>();
}
}



We can run the following to show that the objects get create and populate the services:



static void Main(string[] args)
{
BusinessLogic bz;

bz = NormalWay();
System.Console.WriteLine(bz);

bz = UnityWay();
System.Console.WriteLine(bz);

bz = NinjectWay();
System.Console.WriteLine(bz);

}

So the end result is that we can design our components and use constructor-injection. So long as we keep container-dependencies out of our business components, an app can be assembled using the container of your choice.

Thursday, July 3, 2008

Looking at Ninject

Not to be too Microsoft-centric, I decided to look at the DI container Ninject, which has recently been released by Nate Kohari. After all, if we write our components correctly (POCOs), then swapping out containers should be a trivial exercise.

I looked at the docs on Ninject's constructor injection and found the following:

You also have the option to leave off the [Inject] attribute completely. This can help if you don't have access to the source code of a class, but you still want to inject dependencies into it. Here's the logic Ninject follows to choose which constructor to call, if none have an [Inject] attribute:

  1. If the type only has a single constructor, Ninject will call it.
  2. If the type has more than one constructor, but has a default (parameterless) constructor available, Ninject will call it. (This also applies to types that have no explicit constructors defined.)

I think that's a deal-breaker. Adding Attributes to my classes is not an option, because I want to maintain container-independency. In order to work correctly with constructor-injection, I need the container to call the container with as many parameters as it can satisfy. I will often have a parameterless constructor in my component to supply default values for the object for legacy code which is not using a container.

I'll take another look at Ninject if the constructor-injection strategy changes. The site has really sweet icons, by the way. Here's a sample:

Fun with C# 3.0 (#3) - Lambda expressions

The addition of LINQ to C#/.NET has really improved the way that we can handle data in our applications. Here's an example.

Suppose we want to write a method to count the number of strings in a list which exceed a certain length. It's not to hard to do with C# 2.0; you iterate over the items, make the comparison, increment a counter and return it. But C# 3.0 makes it simple.

When the namespace System.Linq is included in your file, IEnumerable objects get a load of new extension methods. One of them is Where, which will return a sub-collection of items that match a filter. The filter is defined as a lambda expression that returns a bool. If the item causes the lambda expression to evaluate to true, then the item will be included in the sub-collection. Let's look at some code:

public int NumberLongerThan(List<string> list, int n)
{
var subList = list.Where(
(string str) => str.Length > n
);
return subList.Count();
}


Here we pass in a List<string> and a number. The subList will have the string items that are longer than n characters. Note that we don't have to define the type of subList; the compiler can infer it at compile-time.



Here is the code that uses the method.



List<string> list = new List<string>() { "abc", "def", "GH", "ijKL", "mnop", "QRSTUV", "Wxyz" };
Console.WriteLine(NumberLongerThan(list, 0));
Console.WriteLine(NumberLongerThan(list, 1));
Console.WriteLine(NumberLongerThan(list, 2));
Console.WriteLine(NumberLongerThan(list, 3));


This is the lambda expression:



(string str) => str.Length > n


It states that a string is passed in and returns a bool based on the test of the string Length. The Where() method takes an expression that expects a string and returns a bool. Since the compiler knows this, we can let it infer the type of the parameter and specify the expression like so:



str => str.Length > n


Also, note that if we have a named method that is of the correct delegate type (Func<T, bool>), we can pass it to Where(). Here, List<T> is List<string>, so the method must take a string parameter.



public bool TestString(string s) { return s.Length > 3; }


var filtered = list.Where(TestString);
//-- or --
Func<string, bool> f = TestString;
var list2 = list.Where(f);


The advantage of using the unnamed lambda expression is that we can reference the local variable n as a parameter in our test expression.



More info at Charlie Calvert's blog.

Saturday, June 28, 2008

Friday, June 27, 2008

Nice series on Separation of Concerns by bogardj

Jimmy Bogard has written a great series of blog posts showing how to refactor some Data Access code to make it more readable, testable and maintainable. The offending (offensive?) code was found in ASP.NET Pro magazine and had static references that precluded doing any unit testing. Jimmy shows how to separate out those dependencies.

Tuesday, June 24, 2008

Fun with C# 3.0 (#2)

This one is a quickie. Auto-implemented properties.

It allows you specify the property and have the compiler automatically define a backing private instance member. It is way cool.

public class Employee
{
public string Name { set; get; }
public string Job { set; get; }
public int Age { set; get; }
}

Fun with C# 3.0 (#1)

This is the first in a series of posts in which I explore new features of C# 3.0 available in Visual Studio 2008.

In this post, I introduce anonymous types and extension methods.

An anonymous type is an unnamed class that you can define simply by specifying the values of its properties. These properties are read-only and can be accessed through the usual property accessor syntax.

var employee = new { Name = "John Smith", Age = 44, Job = "Manager" };
Console.WriteLine(employee.Name);
Console.WriteLine(employee.Age);
Console.WriteLine(employee.Job);


ProcessData(employee);



The class is created at compile-time and the properties are available via IntelliSense. Note, however that if you want to pass the object to another method, it must be passed as an object, since the class is unnamed.



public void ProcessData(object data)


{


}




Once we have the object in our ProcessData method, we need to access the properties via Reflection. Here's where extension methods come in handy. An extension method is a method that is declared as a static method in static class and is in an accessible namespace. It will appear to add new methods to an object type. For example, I can add a method to the String class that removes spaces:



public static class Extend
{
public static string RemoveSpaces(this string s)
{
return s.Replace(" ", "");
}

}




The "this" parameter modifier indicates that it is an extension method and the type of the parameter (string) is the class that is modified. It is called like so:



Console.WriteLine(employee.Name.RemoveSpaces());

To ease the access to our anonymous type properties, we can create an extension method on the object class. The method will be called ValueOf() and will take the name of the property as a parameter:

public static class ReflectionExtensions
{
public static object ValueOf(this object obj, string name)
{
if (name == null) throw new ArgumentNullException("Property Name");

try
{
return obj.GetType().GetProperty(name).GetValue(obj, null);
}
catch (NullReferenceException)
{
return null;
}
}
}

Now in our ProcessData() method we can access the Property values:

public void ProcessData(object data)
{
Console.WriteLine("Employee Name = " + data.ValueOf("Name"));
Console.WriteLine("Employee Age = " + data.ValueOf("Age"));
Console.WriteLine("Employee Job = " + data.ValueOf("Job"));

}








Wednesday, June 18, 2008

Configuring and Supplying a Factory with Unity

Here is a code-sample which allows the Factory to be Container-dependent, and thus configurable in the container setup code. Notice that I registered the unity instance with itself. If you do not do this, when the Factory is created, Unity will see that a UnityContainer is needed by the constructor and instantiate a new UnityContainer, which will not have the correct configuration. If you have registered the configured unity instance, then it will be supplied to the Factory. Also note that the unity configuration can be changed by other parts of the application, so if you want to avoid that, you might want to make a copy of the container inside the Factory constructor.

using System;
using Microsoft.Practices.Unity;
namespace DI
{
#region Container-independent

public interface I { }
public interface IFactory<T>
{
T Create();
}

public class A : I
{
}
public class Aprime : I
{
}
public class B
{
IFactory<I> Ifactory;

public B(IFactory<I> f) { Ifactory = f; }

public void SomeMethod()
{
I a = Ifactory.Create();
Console.WriteLine(a.ToString());
}
}

#endregion
//--------------------------------------------------------------------------------
#region Unity container Dependent

public class Factory<T> : IFactory<T> where T : class
{
UnityContainer container;
public Factory(UnityContainer unity) { this.container = unity; }
public T Create() { return container.Resolve<T>(); }
}
class Program
{
static void Main(string[] args)
{
UnityContainer unity = new UnityContainer();

// register the Unity container so that this instance is provided to factory
unity.RegisterInstance(unity);

// tell Unity to provide A when asked for interface I
unity.RegisterType<I, A>();

// use the Unity enabled factory
unity.RegisterType(typeof(IFactory<I>), typeof(Factory<I>));

B b = unity.Resolve<B>();
b.SomeMethod();

// now tell Unity to provide Aprime when asked for I
unity.RegisterType<I, Aprime>();
b.SomeMethod();

}
}
#endregion
}

See: http://www.codeplex.com/unity/Thread/View.aspx?ThreadId=29697 for a discussion about this.

Container Dependency anti-pattern

It is good design to minimize the number of dependencies between components in a system. Dependency Injection is used to decouple components from each other. A component should not specify, or require, a particular implementation of a Data Service, Logging Service or any other cross-cutting concern.

One solution to this problem is to use a DI container, such as Unity. This localizes all the dependencies in one place, the shell, or configuration point for your application. The components and services can be assembled and provided to the components as needed.

However, sometimes this leads to an anti-pattern in that components are built with a dependency on the container. This counteracts much of the advantage of using the container. It makes it difficult to share your components with another team that might be using a different container. Do not create container dependencies in your components!

The picocontainer example shows how to solve the problem with constructor injection, but assumes that the dependent container (B) only needs one instance of the A object. The question arises how can B create A objects on the fly as needed?

The solution is to inject a Factory into B via the constructor.

using System;
using Microsoft.Practices.Unity;

namespace DI
{
public class A
{
}

public class B
{
Factory<A> Afactory;

public B(Factory<A> f) { Afactory = f; }

public void SomeMethod()
{
A a = Afactory.Create();
Console.WriteLine(a.ToString());
}
}

public class Factory<T> where T : new()
{
public T Create() { return new T(); }
}
class Program
{
static void Main(string[] args)
{
UnityContainer unity = new UnityContainer();
B b = unity.Resolve<B>();
b.SomeMethod();
}
}
}


If you want to have the factory use a specific container, that could be an acceptable dependency, since it would be a trivial change to write a new Factory class for a different container. I will post this later.

See: http://www.codeplex.com/unity/Thread/View.aspx?ThreadId=29697 for a discussion about this.

UPDATE: See http://initializecomponent.blogspot.com/2008/10/common-service-locator.html

Tuesday, June 17, 2008

Stupid .NET Tricks #1

If you like to Unit Test as much as I do, and you're obsessive about putting your strings in Resources files, it can be kind of tricky to make use of these Resources in your Unit Tests.

I'll show you what I mean. You want to unit test the following:

public string login(user, pw)
{
if (!validUser(user, pw))
{
return "Invalid User";
}
}

OK, so we write a test:

public void TestInvalidUser()
{
MyClass m = new MyClass();
Assert.AreEqual("Invalid User", m.login("Me","X"));
}

Now I want to move the error message into the Resources class that Visual Studio generates for you when you use the String editor on the Project Properties dialog. Now we have:

public string login(user, pw)
{
if (!validUser(user, pw))
{
return Properties.Resources.INVALID_USER;
}
}

and

public void TestInvalidUser()
{
MyClass m = new MyClass();
Assert.AreEqual(Properties.Resources.ERROR_INVALID_USER, m.login("Me","X"));
}

The problem is that the Resources class that VS generates for you will have the internal access modifier and will not be accessible to your test code (unless you include the test in the same assembly, which is sub-optimal). To the rescue comes the InternalsVisibleTo attribute. Add it to your production class, specifying the Test assembly as a friend and you code will compile. I've had mixed success getting Intellisense to recognize that it can access the other assembly, however. It doesn't stop it from compiling anyway.

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("AcmeCorp.ProjectX.Tests.TestSecurity")]

Note, also, that if the production assembly is signed, then the test assembly will need to signed as well, and the public key of the friend assembly will need to be specified as part of the assembly name.

Saturday, June 7, 2008

Silverlight 2 Beta 2 available

Microsoft has released the Second Beta of Silverlight 2.

Announcement on Scott Guthrie's blog.

The highlights:
  • 4.8 MB Download that does not require .NET Framework on the target system
  • The tools for VS 2008 will work with VS 2008 and VS 2008 SP1 beta
  • Adds more controls to beta 1
  • Cross-domain socket support
  • Background thread networking
  • Support for WCF duplex connections
  • Datagrid improvements
  • Databinding improvements
  • Isolated storage is now 1MB with ability to prompt user to increase storage space

Note that if you want to use VS 2008 SP1 with SL 2 Beta 2, you should install VS 2008 SP1 beta first then the SL2B2 tools.

Thursday, June 5, 2008

Unity, WCF and IIS

In a previous post, I showed how to integrate Unity with WCF when you are self-hosting a service. What's not clear is how to get IIS to use the Unity-enabled host when it starts hosting your service.

This is accomplished with a ServiceHostFactory. The @ServiceHost directive has an attribute named, curiously enough, Factory. This can be used to designate a class which will provide a configured ServiceHost. More on that in a moment. Let's see an example of a service that needs constructor-injection.

I've taken the default Service that Visual Studio 2008 gives you when you create a WCF Web Service, and added a SuffixProvider dependency that is satisfied in the constructor.



namespace WcfService1
{
public class Service1 : IService1
{
private ISuffixProvider provider;
public Service1(ISuffixProvider provider)
{
this.provider = provider;
}

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

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += provider.GetSuffix();
}
return composite;
}
}
}

namespace WcfService1
{
public interface ISuffixProvider
{
string GetSuffix();
}
}


namespace WcfService1
{
public class MySuffixProvider : ISuffixProvider
{
#region ISuffixProvider Members

public string GetSuffix()
{
return "estericize";
}

#endregion
}
}



Using the UnityWCF project created in the previous post, I will create a factory that is derived from ServiceHostFactory, and configure a Unity container to supply a concrete implementation of ISuffixProvider. I have done this in code, most likely you will want to configure it from an XML file.



using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Microsoft.Practices.Unity;
using UnityWCF;

namespace WcfService1
{
public class UnityServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(
Type serviceType, Uri[] baseAddresses)
{
UnityServiceHost host = new UnityServiceHost(serviceType, baseAddresses);
UnityContainer unity = new UnityContainer();
host.Container = unity;

//configure container
unity.RegisterType<ISuffixProvider,MySuffixProvider>();

return host;
}
}
}


Finally, edit the Service1.svc file to reference the factory class:

<%@ ServiceHost Language="C#"
Debug="true"
Factory="WcfService1.UnityServiceHostFactory"
Service="WcfService1.Service1"
CodeBehind="Service1.svc.cs" %>

Unity and Interception

Matthew Podwysocki has a good post on adding Interception capabilities to Unity via its extension model.

His conclusion:

As you can see, the extensibility model of Unity works in that we can add
interception to Unity. So, we can start thinking about moving our cross
cutting concerns to these layers should we so choose if Unity is your container
of choice. There are plenty of containers out there to choose from, so
it's best to give them all a try and pick one based upon features, programming
style, and heck, maybe even licensing.



UPDATE: It looks like the Interception Extensions that Matt mentions in his post only work with Unity 1.0. Hopefully someone will update them for Unity 1.1 soon.

Wednesday, June 4, 2008

Integrating Unity with WCF

Update (Feb 14, 2012): I fixed an issue in the code.

You might think Unity is great and all, but how can you use it with your WCF services? You might have a service that depends on a data access object, a security object and a logger. How do you get references to these objects into your services when WCF is instanciating your service for you?

You could create static methods that locate and configure these services, like so:

MyLogger logger = MyLogger.getLogger();
MyDAO dao = MyDAO.getDao();
MySecurity security = MySecurity.getSecurityObject();

We all know why that's bad (tightly coupled). We can't change the implementation of any of these objects, or do unit testing with mocks, without changing the code.

With Unity, or any other DI container, we can configure the container and let it resolve the dependencies. Any object that is needs a reference to another object can have it injected through the constructor. All automatically. So how do we force WCF to use the Unity container to create a fully functional service instance for us with all the dependencies resolved? The key is through the magic of an InstanceProvider.

Before I reveal how this is done, I want to show three use cases that we want to be able to solve, and allude to a fourth. These three use cases will be for self-hosted WCF services.

  1. We have a configured Unity container, and want to create a ServiceHost that will use it.
  2. We have a configured Unity container, and an existing ServiceHost instance needs to use it.
  3. We have an existing ServiceHost instance and want to configure it with a new Unity configuration.
Here is what these use cases will look like in code:

Case 1

// Create new ServiceHost
UnityServiceHost host = new UnityServiceHost(typeof(MyService));
host.AddServiceEndpoint(typeof(IService), binding, address);

// Set existing UnityContainer
host.Container = unity;
host.Open();


Case 2

// Create new ServiceBehavior
UnityServiceBehavior behavior = new UnityServiceBehavior();
// Set existing UnityContainer
behavior.InstanceProvider.Container = unity;

// Add behavior to ServiceHost
behavior.AddToHost(host);

host.Open();

Case 3

// let behavior create a new container
UnityServiceBehavior = new UnityServiceBehavior();
// configure new container
behavior.InstanceProvider.Container.RegisterInstance(logger);

behavior.InstanceProvider.Container.RegisterInstance(dao);

behavior.InstanceProvider.Container.RegisterType(typeof(MySecurity));
// Add behavior to ServiceHost
behavior.AddToHost(host);
host.Open();


The fourth use case is running as an IIS-hosted service, which I will leave for a future post.


Creating an InstanceProvider

When WCF needs to create an instance of a service it invokes an instance provider. The default will create the appropriate type using the default constructor, but we can add a ServiceBehavior that will substitute our custom InstanceProvider. Our provider will be configured with a Unity container and call Resolve() when asked for a new Instance.

using System;

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

using Microsoft.Practices.Unity;

namespace UnityWCF
{
public class UnityInstanceProvider : IInstanceProvider
{
public UnityContainer Container { set; get; }
public Type ServiceType { set; get; }

public UnityInstanceProvider() : this(null) {
}

public UnityInstanceProvider(Type type)
{
ServiceType = type;
Container = new UnityContainer();
}

#region IInstanceProvider Members

public object GetInstance(
InstanceContext instanceContext, Message message)
{
return Container.Resolve(ServiceType);
}

public object GetInstance(
InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
public void ReleaseInstance(
InstanceContext instanceContext, object instance)
{
}
#endregion
}
}




Create the Service Behavior

The Service Behavior's ApplyDispatchBehavior method will be called before the service is instanciated. This is the point where we create and configure our InstanceProvider. The AddToHost method is used to add the behavior to the ServiceHost, ensuring that it is only added once.




using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

using Microsoft.Practices.Unity;
using System.Collections.ObjectModel;

namespace UnityWCF
{
public class UnityServiceBehavior : IServiceBehavior
{
public UnityInstanceProvider InstanceProvider
{ get; set; }

private ServiceHost serviceHost = null;

public UnityServiceBehavior()
{
InstanceProvider = new UnityInstanceProvider();
}
public UnityServiceBehavior(UnityContainer unity)
{
InstanceProvider = new UnityInstanceProvider();
InstanceProvider.Container = unity;
}
public void ApplyDispatchBehavior(
ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb
in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher cd
= cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed
in cd.Endpoints)
{
InstanceProvider.ServiceType
= serviceDescription.ServiceType;
ed.DispatchRuntime.InstanceProvider
= InstanceProvider;

}
}
}
}
public void AddBindingParameters(
ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters) { }

public void Validate(
ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase) { }

public void AddToHost(ServiceHost host)
{
// only add to host once
if (serviceHost != null) return;
host.Description.Behaviors.Add(this);
serviceHost = host;
}
}
}


Creating the ServiceHost

The UnityServiceHost will encapsulate a UnityContainer and configure itself with the appropriate InstanceProvider and ServiceBehavior, so that the container will be used to Resolve instances when needed.



using System;
using System.ServiceModel;

using Microsoft.Practices.Unity;

namespace UnityWCF
{
public class UnityServiceHost : ServiceHost
{
public UnityContainer Container { set; get; }

public UnityServiceHost()
: base()
{
Container = new UnityContainer();
}

public UnityServiceHost(
Type serviceType,
params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
Container = new UnityContainer();
}

protected override void OnOpening()
{
new UnityServiceBehavior(Container)
.AddToHost(this);
base.OnOpening();
}
}
}



I have to credit Oran Dennison who showed how to integrate WCF and Spring.NET.