Posts tagged with: inversion-of-control

Griffin.Container: Register services using your own attribute.

As you might now, I recommend that you register most classes using the [Component] attribute. However, you might not want to add an external dependency to all class libraries. You can avoid that now with a new feature. And that is to use your own attribute.

You can of course use the feature to customize the registration process. Let say that we’ve created a new attribute called ContainerServiceAttribute, so that we can decorate one of our classes:

[ContainerService]
public class SomeService
{
}

To register all classes with the new attribute use the following:

var registrar = new ContainerRegistrar(Lifetime.Transient);

// the new magic.
registrar.RegisterUsingAttribute<ContainerServiceAttribute>(Assembly.GetExecutingAssembly());

var container = registrar.Build();

The attribute itself is responsible of the registration. Here is a simplistic example:

class ContainerServiceAttribute : Attribute, IAttributeRegistrar
{
    public void Register(Type concrete, IContainerRegistrar registrar)
    {
        //concrete = decorated class. In this case "SomeService"
        registrar.RegisterConcrete(concrete, Lifetime.Default);
    }
}

Use the type to decide which interfaces etc that the class should be registered as.

The feature is available in version 1.0.3. Install it using nuget.

Code is available at github.


Resolving all services through dependency injection in Griffin.Container

I’ve just added a new feature to Griffin.Container: Support for resolving all implementations of a service by using constructors.

You can now do something like this:

public interface IStatefulService
{
	void Ping();
}

public class FtpConnection : IStatefulService
{
}

public class Pop3Connection : IStatefulService
{
}

public class ConnectionPinger
{
	public ConnectionPinger(IEnumerable<IStatefulService> services)
	{
		_services = services;
	}
	
	public void PingAll()
	{
		_services.Each(x => x.Ping());
	}
}

Griffin.Container can be found at github.



Griffin.Container – “The drunken IoC container”

(I started writing this blog entry at friday night, but somehow I didn’t manage to finish it.)

My son has just fallen asleep and wifey is working. Which means that I got a friday night all by myself. So I’ve put some beer and Bacardi Breezers (kinda girly, I know. But I can’t help myself) in a nice row on my desk. Instead of continuing to code on my next entrepenural endeavor I’ve decided to do something fun and challenging. And that is to code an inversion of control container in three hours (until the boss get’s home). (It took another two hours today to clean up the nonsense in this blog entry)

It’s my third attempt during the last couple of years. My both last attempts was just a bit of fooling around and this time I’ve decided to try to create a lean killing machine. So I’ve come up with a slightly different approach compared to my last attempts.

The responsibility

In my eyes an IoC container has three responsibilites. Hence I’ve divided the container into three different classes.

Registration

A container got to be able to register the services that should be provided. I hate those XML configurations since it’s hard to discover configuration errors. I also cry when I have to use API’s which heavily uses extensions methods, since the intellisense for them is messy and hard to understand.

I’ve therefore created three types of registration options:

The attribute

Registration through attributes. Works quite nicely. Create a class and add the [Component] attribute on it. Repeat for all classes in all of your assemblies.

[Component]
public class MyClass : IService
{
}

Control the lifetime:

[Component(Lifetime = Lifetime.Singleton)]
public class MyClass : IService
{
}

And register everything using:

registrar.RegisterComponents(HostingEnvironment.MapPath("~/bin"), "*.dll));

Done.

The module

You can also control the registration process through modules. Great since each module/namespace/section can itself decide what should be registered in the container.

public class UserManagementModule : IContainerModule
{
    public void Register(IContainerRegistrar registrar)
    {
        registrar.Register<UserService>();
    }
}

Then just load all modules:

// can also specify path + filepattenr as the example above.
registrar.RegisterModules(Assembly.GetExecutingAssembly());

The traditional approach

There are also the traditional RegisterXxxxx methods.

public interface IContainerRegistrar
	IEnumerable<ComponentRegistration> Registrations { get; }

	void RegisterComponents(Lifetime defaultLifetime, string path, string filePattern);
	void RegisterComponents(Lifetime defaultLifetime, params Assembly[] assemblies);

	void RegisterModules(string path, string filePattern);
	void RegisterModules(params Assembly[] assemblies);

	void RegisterConcrete<TConcrete>(Lifetime lifetime = Lifetime.Scoped) where TConcrete : class;
	void RegisterConcrete(Type concrete, Lifetime lifetime = Lifetime.Scoped);

	void RegisterService<TService>(Func<IServiceLocator, object> factory, Lifetime lifetime = Lifetime.Scoped);
	void RegisterService(Type service, Func<IServiceLocator, object> factory, Lifetime lifetime = Lifetime.Scoped);

	void RegisterType<TConcrete, TService>(Lifetime lifetime = Lifetime.Scoped)
		where TService : class
		where TConcrete : class;
	void RegisterType(Type concrete, Type service, Lifetime lifetime = Lifetime.Scoped);

	void RegisterInstance<TService>(TService instance) where TService : class;
	void RegisterInstance(Type service, object concrete);
}

The build plan

Performance is important. And you can’t get performance if you do not analyze how each service should be built (before the actual service location). I therefore go through all classes, check their dependencies and create a plan for how they should be built. I then analyze which classes is used by which services and create a mapping between each service and the implementing classes.

The builder supports multiple constructors. It uses the most specific constructor for which it can resolve all dependencies for.

/// <summary>
/// Used to build the container.
/// </summary>
public interface IContainerBuilder
{
    /// <summary>
    /// Builds a container using the specified registrations.
    /// </summary>
    /// <param name="registrar">Registrations to use</param>
    /// <returns>A created container.</returns>
    IParentContainer Build(IContainerRegistrar registrar);
}

Service location

The container itself IS implementing the service location pattern. Hence the container interface is really a service location interface and we’ll use that as our base.

public interface IServiceLocator
{
    bool IsRegistered(Type type);
    T Resolve<T>() where T : class;
    object Resolve(Type service);
    IEnumerable<T> ResolveAll<T>() where T : class;
    IEnumerable<object> ResolveAll(Type service);
}

The container itself have been divided into two containers. A parent container which is the one generated by the builder and a scoped container.

public interface IParentContainer : IServiceLocator
{
    IChildContainer CreateChildContainer();
}

public interface IChildContainer : IServiceLocator, IDisposable
{
    
}

Scoped services can only be resolved by a scoped container. So you got to use something like this:

using (var scoped = container.CreateChildContainer())
{
    // All scoped services which is resovled here
    // will be disposed automatically.
}

That should make it easier to handle scoping in WCF, MVC3 and similar frameworks.

Extension points

The divided architecture allows you to customize the container quite nicely.

Custom registration

  • Inherit ContainerRegistrar and override Add to be able to handle all registrations.
  • Override CreateRegistration to control which interfaces a class can implement
  • Pass a custom IServiceFilter class to the ContainerRegistrar to filter out which service all classes can be registered for.

Building

  • Inherit ContainerBuilder and override TryGetConstructor to be able to control which constructor the builder should use.

Service location

  • Inherit Container and ChildContainer and override the GetInstance method to get full control over the returned instances. Perfect approach if you want to generate proxies or use AOP.

Usage

public class IntegrationTests
{
    [Fact]
    public void SimpleRegistrationTransient()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>(Lifetime.Transient);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instance1 = container.Resolve<MySelf>();
        var instance2 = container.Resolve<MySelf>();

        Assert.NotSame(instance1, instance2);
    }


    [Fact]
    public void OneDependencySingleton()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>(Lifetime.Transient);
        registrar.RegisterType<OneDepencency>(Lifetime.Singleton);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instance1 = container.Resolve<OneDepencency>();
        var instance2 = container.Resolve<OneDepencency>();

        Assert.Same(instance1, instance2);
    }

    [Fact]
    public void ResolveAllStartable()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<Startable1>(Lifetime.Singleton);
        registrar.RegisterType<Startable2>(Lifetime.Singleton);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instances = container.ResolveAll<ISingletonStartable>();

        Assert.Equal(2, instances.Count());
    }

    [Fact]
    public void ResolveFromComponents()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterComponents(Lifetime.Singleton, Assembly.GetExecutingAssembly());
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        container.Resolve<OneDepencency>();
    }

    [Fact]
    public void ResolveFromModules()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterModules(Assembly.GetExecutingAssembly());
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        container.Resolve<MySelf>();
    }

    [Fact]
    public void ChildContainer()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>();
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        MySelf instance;
        using (var childContainer = container.CreateChildContainer())
        {
            instance = childContainer.Resolve<MySelf>();
        }

        Assert.True(instance.IsDisposed);
    }
}

Performance

I used the benchmark testing code which have been created by Daniel Palme.

Name                    Singleton       Transient       Combined        #.ctor Singleton        #.ctor Transient        #.ctor Combined
No                      30              37              45              1                       2000001                         1000000
AutoFac                 582             2635            6225            1                       2000001                         1000000
Dynamo                  65              66              113             1                       2000001                         1000000
Funq                    74              87              231             1                       2000001                         1000000
Hiro                    104             99              109             1                       2000001                         1000000
LightInject             92              90              98              1                       2000001                         1000000
Munq                    91              108             342             1                       2000001                         1000000
Petite                  67              70              210             1                       2000001                         1000000
SimpleInjector          71              81              101             1                       2000003                         1000001
StructureMap            925             1032            3318            1                       2000001                         1000000
Unity                   1346            1694            5599            1                       2000001                         1000000
Windsor                 486             2102            6324            1                       2000001                         1000000
Griffin.Container       158             183             471             1                       2000001                         1000000

Chart:

(I had to remove ninject & spring.net from the chart since they are way too slow)

The performance is OK by me since I’ve not done any optimizations yet.

Summary

I’m quite satisfied with the result and a bit suprised that I managed to create the architecture that I did last night. It was really fun and I think that I’ll continue to improve the container so it becomes even more useful.


Inversion of control containers – Best practices

Disclaimer: I’ve used IoC containers for a couple of years now and also made a couple of my own (just to learn, nothing released). I’ve also consumed loads of documentation in the form of blogs and stackoverflow questions. And I thought that I should share what I’ve learned. In other words: These are my very own subjective best practices.

An IoC container is not a Service Locator

One of the first mistakes that you’ll make is to register the container in the container or create a singleton to get access to it. It basically means that you can do something like:

public class MyService
{
    MyService(IServiceResolver myContainer)
    {
    }

    public void DoSomething()
    {
        var service = _container.Resolve<ISomeService>();
        service.DoMore();
    }
}

Do not do that. Service location is another pattern that you get as a “bonus” when you use a IoC container. Some even call Service Location as an anti-pattern. Google it.

The most important reasons is that you hide a dependency that you won’t discover until you forget to register IAnotherService. What if the method is only used during edge cases? Then the dependency wont be discovered until that edge case is fulfilled.

Using the constructor to inject dependencies will also help you discover violations to Single Responsibility principle. Having a lot of dependencies might suggest that you need to break your class into several smaller classes.

There are some cases when you THINK that you really need to use the container in your class. Example:

    public class YourService
    {
        public YourService(IContainer container)
        {
        }

        public void YourMethod()
        {
            var user = _container.Get<IUser>();
        }
    }

The proper solution is to register a factory in the container:

    public class YourService
    {
        public YourService(IDomainModelFactory factory)
        {
        }

        public void YourMethod()
        {
            var user = _factory.Create<IUser>();
        }
    }

The smaller interface, the better

Interfaces are not classes. There is nothing saying that there should be a 1-1 mapping between them. imho it’s far better to create several small interfaces and let the same class implement them than creating a larger one having all all features that the class have.

Do design the interfaces before you design the classes. The reason is that if you do the opposite you’ll usually end up with one interface per class.

Smaller interfaces also makes it easier to let your application grow since you can move smaller parts of the implementation (as in creating a new class for one of the interfaces).

Don’t choose a longer lifetime to get better performance

This is a mistake that I’ve done dozens of times. Object creation will usually not be a problem when you are running your application.

The advantage with short lifetimes is that it get easier to handle context sensitive dependencies such as a database connections.

Using a longer lifetime (which lives longer than the mentioned context sensitive dependencies) usually means that you create same kind of service location implementation or custom factories.

Hence you get code like this:

public class UserService : IUserService
{
    public void Add()
    {
        var (var uow = UnitOfWork.create())
        {
            // do stuff.
            uow.Save();
        }
    }
}

instead of

public class UserService : IUserService
{

    public UserService(IUnitOfWork uow)
    {

    }

    public void Add()
    {
        // do stuff with the unit of work here.
    }
}

what’s the problem with the first approach? Well. It’s usually the CALLER that knows what should be done in a unit of work, not the service itself. I’ve seen people create complex Unit Of Work solutions to get round that problem. The other simpler approach is to use TransactionScope.

Both of those solutions are either slower or more complex than services with shorter lifetime. Save the optimizations to when object instantiation have been proven to be a problem.

Don’t mix lifetimes

Mixing lifetimes can lead to undesired effects if you are not careful. Especially when projects have begun to grow and getting more complex dependency graphs.

Example

// EF4 context, scoped lifetime
class Dbcontext : IDbContext
{
}

// short lifetime, takes db context as a dependency
class Service1 : IService1
{
}

// Single instance, keeps a cache etc.
class Service2 : IService2
{
}

Service2 takes service1 as a dependency which in turn requires a dbcontext. Let’s say that the dbcontext has an idle timeout which closes the connection after a while. That would make service1 fail and also service2 which depends on it.

Simply be careful when using different lifetimes.

Try to avoid primitives as constructor parameters

Try to avoid using primitives as constructor parameters (for instance a string). It’s better to take in object since it makes extension (subclassing) easier.

Hey, I need my primitives you say. Take this example:

public class MyRepository
{
    public MyRepository(string connectionString)
    {
    }
}

Well. You’re class breaks SRP. It acts as a connection factory and a repository. Break the factory part out:

public class MyRepository
{
    public MyRepository(IConnectionFactory factory)
    {
    }
}

Avoid named dependencies

Named dependencies are as bad as magic strings. Don’t use them.

If you need different implementations simply create different interfaces such as IAccountDataSource and IBillingDataSource instead of just taking in IDataSource.

imho this is a possible violation of Liskovs Substitution principle.