Building an IoC Container – Resolving Types without Dependencies

The code for this step is located here.

As noted in the introduction, we are going to take this in steps and go in a test first manner.  So, let’s write our first test.

public class when_resolving_a_type_with_zero_dependencies : ContainerSpecBase
{
    static object _result;

    Because of = () =>
        _result = _container.Resolve(typeof(DummyService));

    It should_not_return_null = () =>
        _result.ShouldNotBeNull();

    It should_return_an_instance_of_the_requested_type = () =>
        _result.ShouldBeOfType();

    private class DummyService { }
}

If you haven’t used Machine.Specifications, this may seem like odd syntax.  But what I like about it is that it is easy to see what is going on when the container is resolving a type with zero dependencies.  First,  the container shouldn’t return null and second, the container should return an instance of the requested type.

Now that we have a test, we are going to start coding the implementation.  We’ll start with the simplest thing that could possibly work here.

public class Container
{
    public object Resolve(Type type)
    {
        return Activator.CreateInstance(type);
    }

    public T Resolve()
    {
        return (T)Resolve(typeof(T));
    }
}

Nothing special, and nothing that you couldn’t have figured out on your own.  In the next post, we’ll see how to handle this when the requested type has dependencies.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s