Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do IDisposable objects get disposed at the end of a Nancy request using the RequestContainer?

I'm registering a DbContext onto the TinyIoCContainer that's passed into the ConfigureRequestContainer method on the DefaultNancyBootstrapper.

Whilst this works fine, I've noticed that the Dispose method on the context is never called once a request has completed. I'd expect the DbContext to be disposed of after a request to close the connection (we're using SQLite).

Q: Are disposable instances actually disposed at the end of a request within the TinyIoCContainer?

Bootstrapper

protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
    base.ConfigureRequestContainer(container, context);

    container.Register<IContext>((_,__) => 
    {
        // Code here to get connection string
        return new Context(new SQLiteConnection(connString), true);
    });
}

Context

public interface IContext : IDisposable
{
    ...
}

public class Context : DbContext, IContext
{
    ...

    public new void Dispose()
    {
        base.Dispose();  // This never gets called
    }
}

Update

The marked answer was ultimately correct. I basically had to do something like so:

if (string.IsNullOrEmpty(context.Request.UserHostAddress))
{
    container.Register<IContext>((_,__) => null);
}
else
{
    // Get username from request headers
    // Build up SQLite connection string based off username
    var dbContext = new Context(new SQLiteConnection(connString));
    container.Register<IContext>(dbContext);
}
like image 757
Tom Avatar asked Dec 05 '25 20:12

Tom


1 Answers

I think its because you're using the manual factory registration, it expects you to control lifetime yourself. You probably don't want to be using that anyway, as you are creating a new context every time you ask for one with the code you have there - switch it to an instance registration and you should be ok.

container.Register<IContext>(new Context(new SQLiteConnection(connString), true));
like image 101
Steven Robbins Avatar answered Dec 08 '25 09:12

Steven Robbins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!