May 6, 2008

Unity Application block and Generic Singleton

Here are some features of the Unity Application block. (Note there is overhead in using this block… i.e. overhead while creating instances of objects that have dependent objects)

  Highlights of the Unity Application Block

The Unity Application Block includes the following features:

· It provides a mechanism for building (or assembling) instances of objects, which may contain other dependent object instances.

· It exposes RegisterType methods that support configuring the container with type mappings and objects (including singleton instances) and Resolve methods that return instances of built objects that can contain any dependent objects.

· It provides inversion of control (IoC) functionality by allowing injection of preconfigured objects into classes built by the application block. Developers can specify an interface or class type in the constructor (constructor injection) or apply to properties and methods attributes to initiate property injection and method call injection.

· It supports a hierarchy for containers. A container may have child container(s), allowing object location queries to pass from the child out through the parent container(s).

· It can read configuration information from standard configuration systems, such as XML files, and use it to configure the container( The Unity Container which hold references to the objects built using Resolve method).

· It makes no demands on the object class definition. There is no requirement to apply attributes to classes (except when using property or method call injection), and there are no limitations on the class declaration.

· It supports custom container extensions that developers can implement; for example, methods to allow additional object construction and container features such as caching.

And here is the code for the Generic Singleton:

/// <summary>
/// Provides a Singleton implementation using Generics.
/// </summary>
/// <typeparam name="T">Type of singleton instance</typeparam>
public sealed class Singleton<T> where T : new()
Singleton() { }
public static T Instance
{ return Nested.instance; }

class Nested
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }
internal static readonly T instance = new T();

The code for returning the instance then becomes:

        public static BlogSettings Instance
return Utils.Singleton<BlogSettings>.Instance;

You have to also change the constructor for BlogSettings to public to allow this this to work

kick it on