DB connection is not closed after request ends in

2019-08-01 13:03发布

问题:

I'm building a Nancy web app, and using OrmLite for DB access. I noticed that every request opens up a new DB connection and doesn't close it. I thought that registering the OrmLiteConnection class in the Application container would make it application-scoped, but it looks like I'm missing something.

Here's my code (in ConfigureApplicationContainer):

container.Register<OrmLiteConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
container.Register<OrmLiteConnection>(
            (cContainer, overloads) => (OrmLiteConnection) cContainer.Resolve<OrmLiteConnectionFactory>().Open());

回答1:

You need to add scope to your registration(s):

container
    .Register<OrmLiteConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider))
    .AsSingleton(); // I think this is by default, but sometimes being explicit is good.

container
    .Register<OrmLiteConnection>(
        (cContainer, overloads) => (OrmLiteConnection) cContainer.Resolve<OrmLiteConnectionFactory>().Open())
    .AsPerRequestSingleton();;

AFAIK, this will ensure the instances are disposed at the scope's end. Therefore, if you need to do more than Dispose() then you might need to find some way of supplying a delegate that can executed at that time.



回答2:

I moved registration of OrmLiteConnection to ConfigureRequestContainer. Then I overrode RequestStartup and added:

pipelines.AfterRequest += (ctx) => {
    //close the connection
    container.Resolve<OrmLiteConnection>().Dispose();
};