0

My (Non-thread safe) wrapper for Castle Windsor IoC

by klh 24. marts 2009 03:58

I have a small wrapper API that I use around Castle Windsor, and thought I would share it. You could probably use it to wrap an IoC of your own choice.

First please note that this library is not checked for thread safety, secondly there is nothing original in what I do, it’s just my take on what’s already been done.

Here is how I configure the IoC container:

private static void SetupIOC() { Bind<HTTPClientWithBasicAuth>.To<IHTTPClient>(); Bind<TwitterClient>.ToAbstraction<ITwitterClient>(); }

Here is how I resolve an object:

ITwitterClient twitterClient = ResolveType.Of<ITwitterClient>();

Here is how you bind an instance to an interface or class:

Bind<UsernamePassword>.ToInstance(new UsernamePassword(args[0], args[1]));

 

Here is the class I use to resolve an object. This code is tightly coupled to the Windsor container, and for my pet project it is fine, but you might want to couple loosely to the container.

public static class ResolveType
{
private static readonly IWindsorContainer _container;
static ResolveType()
{
_container = new WindsorContainer();
}
public static T Of<T>() where T : class
{
if (typeof (T).Equals(typeof (IWindsorContainer)))
{
return new WindsorContainer() as T;
}
return _container.Resolve<T>();
}
internal static void AddComponent(string key, Type serviceType, Type classType)
{
_container.AddComponent(key, serviceType, classType);
}
internal static void AddComponentInstance<T>(object instance)
{
_container.Kernel.AddComponentInstance<T>(instance);
}
}

The two AddInstance methods are internal since the Bind class lives in the same assembly.

Here is how i configure the IoC container:

 

public class Bind<T>
{
public static void ToAbstraction<S>()
{
ResolveType.AddComponent(typeof (S).ToString(), typeof (S),
typeof (T));
}
public static void ToInstance(object instance)
{
ResolveType.AddComponentInstance<T>(instance);
}
}
You can find a small solution using this here 

Edit:

Renamed Bind.To to Bind.ToAbstraction, but not in the downloadable solution.

Tags:

C# | IoC

Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft