Introduction
Last week, I was programming a Compact Framework application. I'm so used to IoC right now that I hardly see myself programming in another way. The problem is that Windsor (my favorite) container doesn't work on CF. So I looked at my options. It turned out there weren't many. Actually I found some. One of them: Ninject, although very promising implied some study, because it ain't a container, and I didn't get the time then. There were another couple that worked pretty similar to Windsor, but they had problems resolving generic components. So I thought: I want my own!!!
Changes
- 18-Jun-2011: The
IService
interface wasn't that useful, if at all. So, every use of it has been replaced with object
. For the reader who sees this article for the first time: never mind. - 18-Jun-2011: Generics registration improved, there were some cases causing problems, they are not anymore.
- 15-May-2012: References on IoC and DI added.
Building an IoC from Scratch
Let's start with the interfaces:
public interface IServicesContainer
{
TService Resolve<TService>();
object Resolve(Type tService);
}
public interface IServicesRegistrar : IServicesContainer
{
void RegisterForAll(params Type[] tServices);
void RegisterForAll(IEnumerable<Type> tServices);
void RegisterFor(Type tService, params Type[] tInterfaces);
void RegisterFor(Type tService, params IEnumerable<Type> tInterfaces);
}
Code Excerpt 1: IoC interfaces
Everything we might need is there. The actual container IServicesContainer
, and a registrar IServicesRegistrar
. A container should implement both IServicesContainer
and IServicesRegistrar
, but the registrar is only needed when registering so later on we could use only the container itself.
We will need a helper type for storing information about types and instances:
internal class ServiceDescriptor
{
public Type ServiceType { get; set; }
public object Instance { get; set; }
}
Code Excerpt 2: ServiceDescriptor
Let's start with the container:
internal class ServicesContainer : IServicesRegistrar
{
private readonly IDictionary<Type, ServiceDescriptor> _services =
new Dictionary<Type, ServiceDescriptor>();
public TService Resolve<TService>()
{
return (TService)Resolve(typeof(TService));
}
public object Resolve(Type tService)
{
return GetInstance(tService);
}
...
}
Code Excerpt 3: The Container, Most Of It
A dictionary would hold the mappings. GetInstance
would find the existing instance or create a new one. Let's continue with GetInstance
:
internal class ServicesContainer : IServicesRegistrar
{
...
private object GetInstance(Type tService)
{
if (_services.ContainsKey(tService))
return GetInstance(_services[tService]);
var genericDefinition = tService.GetGenericTypeDefinition();
if (_services.ContainsKey(genericDefinition))
return GetGenericInstance(tService,
_services[genericDefinition].ServiceType);
throw new Exception("Type not registered" + tService);
}
...
}
Code Excerpt 4: GetInstance
There are three cases:
- The type is known, if so, we ask for
GetInstance
but this time with the ServiceDescriptor
as parameter, this overload will be next. - The type is unknown, but maybe it is a generic type, and its generic type definition is known, if so, we ask
GetGenericInstance
to solve the problem. - The type is unknown, you've seen this movie so there is no need to tell you what happens next.
internal class ServicesContainer : IServicesRegistrar
{
...
private object GetInstance(ServiceDescriptor serviceDescriptor)
{
return serviceDescriptor.Instance ?? ( serviceDescriptor.Instance =
CreateInstance(serviceDescriptor.ServiceType));
}
}
Code Excerpt 5: GetInstance II
Not much here, just resolved an interface to a concrete class, then asked CreateInstance
to instantiate that class. The really interesting stuff happens in CreateInstance
, that's why it will have to wait. Let's look at GetGenericInstance
first:
internal class ServicesContainer : IServicesRegistar
{
...
private object GetGenericInstance(Type tService, Type genericDefinition)
{
var genericArguments = tService.GetGenericArguments();
var actualType = genericDefinition.MakeGenericType(genericArguments);
var result = CreateInstance(actualType);
_services[tService] = new ServiceDescriptor
{
ServiceType = actualType,
Instance = result
};
return result;
}
}
Code Excerpt 6: GetGenericInstance
There generic arguments are taken from actual requested type tService
and a new generic type is created from the registered type and these arguments. Then we request CreateInstance
to help us out. Think it's time:
internal class ServicesContainer : IServicesRegistrar
{
...
private object CreateInstance(Type serviceType)
{
var ctor = serviceType.GetConstructors().First();
var dependecies = ctor.GetParameters()
.Select(p => Resolve(p.ParameterType)).ToArray();
return (IService)ctor.Invoke(dependecies);
}
}
Code Excerpt 7: CreateInstance
First we get a constructor, there should be only one. Then we get the constructor parameter types (dependencies) and resolve them. Finally, we create and return the instance. That's it, we just need to register types and our IoC container would be ready.
internal class ServicesContainer : IServicesRegistrar
{
...
public ITypeRegistrar RegisterForAll(params Type[] implementations)
{
return Register((IEnumerable<Type>)implementations);
}
public ITypeRegistrar RegisterForAll(IEnumerable<Type> implementations)
{
foreach (var impl in implementations)
RegisterFor(impl, impl.GetInterfaces());
return this;
}
public ITypeRegistrar RegisterFor(Type implementation, params Type[] interfaces)
{
return RegisterFor(implementation, (IEnumerable<type>)interfaces);
}
public ITypeRegistrar RegisterFor
(Type implementation, IEnumerable<type> interfaces)
{
foreach (var @interface in interfaces)
_services[GetRegistrableType(@interface)] =
new ServiceDescriptor
{
ServiceType = implementation
};
return this;
}
private static Type GetRegistrableType(Type type)
{
return type.IsGenericType && type.ContainsGeneric ?
type.GetGenericTypeDefinition() : type;
}
}
Code Excerpt 8: Registrar Members
As you can see, there are a couple of changes. ITypeRegistrar
is just a base for IServicesRegistrar
, and all void
members have been replaced with ITypeRegistrar
to allow method chaining.
Generics Registration
Registering generics has 2 cases which had been solved by method GetRegistrableType
. Next section will show an example of each. Let's see the situations:
- Register an open constructed type (generic arguments not specified). Let's call this one an "implicit registration".
- Register a close constructed type (generic arguments have been specified). Let's call this one an "explicit registration".
Let's take a look at both cases in the simplest way:
public interface ITypeNamePrinter<TType>
{
void Print();
}
public class TypeNamePrinter<TType> : ITypeNamePrinter<TType>
{
public void Print()
{
Console.WriteLine(typeof(TType).FullName);
}
}
[TestFixture]
[TestClass]
public class GenericRegistrations
{
[Test]
[TestMethod]
public void ExplicitRegistration()
{
var services = new ServicesContainer();
services.RegisterForAll(typeof(TypeNamePrinter<int>),
typeof(TypeNamePrinter<string>), typeof(TypeNamePrinter<Type>));
services.Resolve<ITypeNamePrinter<int>>().Print();
services.Resolve<ITypeNamePrinter<string>>().Print();
services.Resolve<ITypeNamePrinter<Type>>().Print();
Assert.Throws(typeof(Exception), () =>
services.Resolve<ITypeNamePrinter<float>>().Print());
}
[Test]
[TestMethod]
public void ImplicitRegistration()
{
var services = new ServicesContainer();
services.RegisterForAll(typeof(TypeNamePrinter<>));
services.Resolve<ITypeNamePrinter<int>>().Print();
services.Resolve<ITypeNamePrinter<string>>().Print();
services.Resolve<ITypeNamePrinter<Type>>().Print();
Assert.DoesNotThrow(() =>
services.Resolve<ITypeNamePrinter<float>>().Print());
}
}
Code Excerpt 9: Generics Registrations
Explicit implementation sample registers every type. When asking for one not explicitly registered, an exception is thrown. Implicit registration simply registers the open constructed type and every time you ask the container for a new close constructed type's instance, it creates the registration and the instance for that type. Using combinations of implicit and explicit could result in a very flexible an interesting scenario. To end with this subject, let's look at one, a little more complicated, example with explicit registrations.
public interface IExplicit<TType>
{
void Print();
}
public class StringExplicit : IExplicit<string>
{
public void Print()
{
Console.WriteLine("System.String");
}
}
public class IntExplicit : IExplicit<int>
{
public void Print()
{
Console.WriteLine("System.Int32");
}
}
public class TypeExplicit : IExplicit<Type>
{
public void Print()
{
Console.WriteLine("System.Type");
}
}
[TestFixture]
[TestClass]
public class ExplicitRegistrations
{
[Test]
[TestMethod]
public void Test()
{
var services = new ServicesContainer();
services.RegisterForAll(typeof(StringExplicit),
typeof(IntExplicit), typeof(TypeExplicit));
services.Resolve<IExplicit<int>>().Print();
services.Resolve<IExplicit<string>>().Print();
services.Resolve<IExplicit<Type>>().Print();
}
}
Code Excerpt 10: Explicit registrations
IoC Kingdom
Our new IoC Container is ready. Let's play with it:
public interface IKing : IService
{
IBoss<IGuard> Captain { get; }
IBoss<IMaid> Mistress { get; }
void RuleTheCastle();
}
public interface IServant : IService
{
void Serve();
}
public interface IGuard : IServant
{
}
public interface IMaid : IServant
{
}
public interface IBoss<TServant>
where TServant : IServant
{
TServant Servant { get; }
void OrderServantToServe();
}
public class King : Service, IKing
{
public King(IBoss<IGuard> captain, IBoss<IMaid> mistress)
{
Captain = captain;
Mistress = mistress;
}
public void RuleTheCastle()
{
Console.WriteLine("Rule!!!");
Captain.OrderServantToServe();
Mistress.OrderServantToServe();
}
public IBoss<IGuard> Captain
{
get;
private set;
}
public IBoss<IMaid> Mistress
{
get;
private set;
}
}
public class Boss<TServant> : Service, IBoss<TServant>
where TServant : IServant
{
public Boss(TServant servant)
{
Servant = servant;
}
public TServant Servant
{
get;
private set;
}
public void OrderServantToServe()
{
Servant.Serve();
}
}
public class Guard : Service, IGuard
{
public void Serve()
{
Console.WriteLine("Watch!!");
}
}
public class Maid : Service, IMaid
{
public void Serve()
{
Console.WriteLine("Clean!!");
}
}
Code Excerpt 11: The King and the Castle
A test project has been included along with the solution, it contains this sample, which is a dummy but has everything we need for a test. A couple of types useful for registration are also included, but they are too lame to be explained here.
Before saying good bye, let's see how to use the container.
var services = new ServicesContainer();
services.RegisterForAll(ServicesImplementation .FromAssemblyContaining<IKing>());
var king = services.Resolve<IKing>();
king.RuleTheCastle();
Code Excerpt 12: Using the Container
I hope it will be useful!!! Enjoy!!
References
- Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern
- Wikipedia, Inversion of control