DB connection is not closed after request ends in

2019-08-01 12:51发布

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());

2条回答
一夜七次
2楼-- · 2019-08-01 13:15

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.

查看更多
Animai°情兽
3楼-- · 2019-08-01 13:18

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

pipelines.AfterRequest += (ctx) => {
    //close the connection
    container.Resolve<OrmLiteConnection>().Dispose();
};
查看更多
登录 后发表回答