GoodStuff.Container

This is an implementation of a Service Locator pattern, allowing for Dependency Injection through code. The code is a light-weight variant on the screencast from Daniel Cazulino (CAZU). It heavily depends on lambda's and expression to resolve instances.

Introduction

To register an interface against a concrete implementation:
     var container = new Container();
     container.Register<IDummyInterface>(c => new ConcreteImplementation());


To resolve an instance:

     container.Resolve<IDummyInterface>();


The lamdba expression comes with a references to the container, so to register an interface with multiple depencies, you can do stuff like this:

    container.Register<IInterface1>(c => new Implementation1(c.Resolve<IInterface2>());

Using the container in a web application

A static instance of the container is created in a singleton, living in the website application:

public class ApplicationContext
{
     private static ICanResolveDependencies __container;

     public static ICanResolveDependencies Container
     {
          get
          {
               if(__container == null)
               {
                  lock(typeof(ApplicationContext))
                  {
                      if(__container == null)
                      {
                          __container = new GoodStuff.Container();

                          __container.Register<IWebContext>(c => new HttpContextWrapper(HttpContext.Current) );
                          //etc.
                      }
                  }
               }
               return __container;
          }
      }
}


This GoodStuff.ICanResolveDependencies interface then can be passed along other classes by referencing ApplicationContext.Container.

Last edited Aug 11, 2011 at 9:19 AM by drblame, version 2

Comments

No comments yet.