Search code examples
ravendbnancytinyioc

Resolving constructor dependency on service used in NancyFX


I have the following bootstrap

public class NancyBootStrapper: DefaultNancyBootstrapper
{
    protected override void ConfigureRequestContainer(TinyIoC.TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);

        var ravenSession = container.Resolve< IRavenSessionProvider >().GetSession();
        container.Register( ravenSession );
    }
}

When my Nancy app tries to instantiate BlogService using the following constructor

    public BlogService(IDocumentSession documentSession)
    {
        this.documentSession = documentSession;
    }

the application blows up stating that it can't resolve document session, I have also tried the following within my test method (removing the constructor injection).

    public void BuildCategories()
    {
        var container = TinyIoCContainer.Current;
        documentSession = container.Resolve< IDocumentSession >();
        documentSession.Store(new Category{Title = "test"});
        documentSession.Store(new Category{Title = ".net"});

        documentSession.SaveChanges();
    }

This also blows up, pointing out that it can't resolve documentSession.

Now this is the first time I have used either NancyFX or TinyIoC so I could be doing something fundamentally wrong though I should mention that the documentSession does resolve within a Nancy module..

Can any one offer a fix or some suggestions?


Solution

  • I've been playing & digging into both NancyFx and the TinyIoC code bases and have figured out how to fix this issue... I don't like the fix... but hay it works :)

    Basically, I am creating a RavenDB document session in the bootstrapper method configureRequestContainer as it is best practice to use the request as your unit of work scope.

    Unfortunately anything that is auto wired by tinyIoC within configureApplicationContainer does not have any constructor injection performed using the child container being used by the Nancy request (this includes those that are marked as MultiInstance or as PerRequestSingleton.

    To get around this, you need to re-register any components that depend on your per request components within the same child container.

    As I said, I don't like the fix, but it is ultimately a fix :)