OK, in my last post I promised to show you how to use the ServiceContainer. I’m going to steal code from the Autofac home page, and rewrite it using ServiceContainer.
IServiceContainer container = new ServiceContainer(); container.AddService(typeof(IEngine), (c, t) => new Straight6TwinTurbo()); container.AddService(typeof(ICar), (c, t) => new Skyline(c.GetService(typeof(IEngine)), Color.Black)); ICar car = container.GetService(typeof(ICar)); car.DriveTo("Byron Bay");
Pretty darn similar. Autofac uses a ContainerBuilder and a declarative coding style, but other than this they are very equivalent. However, most containers allow you to specify the "scope", while the BCL ServiceContainer only provides Singleton scope, even when you supply a ServiceCreatorCallback, which is unfortunate. So, although I’ll be using IServiceProvider, I won’t be able to use ServiceContainer, and may consider extending both IServiceProvider and IServiceContainer to account for generics and keyed access.