seesharper / LightInject

An ultra lightweight IoC container
http://www.lightinject.net
MIT License
616 stars 122 forks source link

LightInject.Nancy and unit testing #160

Open robertmircea opened 9 years ago

robertmircea commented 9 years ago

What is the recommended way to use Lightinject Nancy when doing testing using Nancy's testing framework? I would like to use a configurable bootstrapper which is not based on TinyIOC but on Lightinject.

For the moment, I am doing this using ConfigurableBootstrapper:

            var bootstraper = new ConfigurableBootstrapper(with =>
                                                           {
                                                               with.Module<ManagementModule>();
                                                               with.Dependency<IUserValidator>(new MockUserValidator());
                                                           });
            var browser = new Browser(bootstraper
                                , defaults: to=> to.Accept("application/json"));
seesharper commented 9 years ago

Let me know if something like this works out for you.

internal class LightInjectConfigurableBootstrapper : LightInjectNancyBootstrapper
{
    private readonly Action<IServiceRegistry> configure;

    public LightInjectConfigurableBootstrapper(Action<IServiceRegistry> configure)
    {
        this.configure = configure;
    }

    protected override IServiceContainer GetServiceContainer()
    {
        var container = base.GetServiceContainer();
        configure(container);
        return container;
    }
}

Then you can use it in your test like this

var bootStrapper = new LightInjectConfigurableBootstrapper(r => r.Register<IUserValidator, MockUserValidator>());
robertmircea commented 9 years ago

It seems there is some logic for testing scenarios in ConfigurableBootstrapper. It does not tries to detect and load all Nancy modules automatically and it will register only the modules specified in the configuration like above:

with.Module<ManagementModule>();

Can I stop the LightInjectConfigurableBootstrapper trying to detect and register in container all modules, IApplicationStartup and IRequestStartup implementing classes? When doing testing for a module, I don't want my entire application bootstrapped.

For example, I have a NewRelicApplicationStartupTask implementing IApplicationStartup. During test it would bad to send metrics to NewRelic :)

seesharper commented 9 years ago

You could try to override the RegisterTypes method.

robertmircea commented 9 years ago

Could you be more specific please? I've overridden RegisterTypes and I haven't provided any implementation. LightInjectNancyBootstrapper is still looking to resolve my IApplicationStartup implementing classes which it detected automatically.