Wednesday, August 19, 2009

A simple ServiceLocator with support for WCF, Web and Thread contexts

Last week I wrote a very simple ServiceLocator that supports single and multiple instances. It has three different containers:

- WCF: It supports single instances on the same OperationContext.
- Web: It supports single instances on the same HttpContext.
- Thread: It supports single instances on the same Thread.


Every container implements the ISingleInstanceContainer interface:


interface ISingleInstanceContainer
{
  bool IsSuitable { get; }
  T Register<T>(T instance);
  T Resolve<T>();
}


The IsSuitable method evaluates if the context is suitable for every container:


class SingleInstanceWcfContainer : ISingleInstanceContainer
{
  public bool IsSuitable
  {
    get { return OperationContext.Current != null; }
  }
  ...
}


class SingleInstanceWebContainer : ISingleInstanceContainer
{
  public bool IsSuitable
  {
    get { return HttpContext.Current != null; } 
  }
  ...
}


In the following example, you can see how to register the ServiceA as “multiple instances” and the ServiceB as “single instance”:


// Multiple Instances Registration
ServiceLocator.Register<IServiceA>(() => new ServiceA());

// Single Instance Registration
ServiceLocator.Register<IServiceB>(() => new ServiceB()).SingleInstance();

// Resolving Instances
IServiceA serviceA = ServiceLocator.Resolve<IServiceA>();
IServiceB serviceB = ServiceLocator.Resolve<IServiceB>();


Here you can download the code.
.

0 comments: