1

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());
ulu
  • 5,872
  • 4
  • 42
  • 51

2 Answers2

0

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.

David Osborne
  • 6,436
  • 1
  • 21
  • 35
  • The first line doesn't work -- says, Nancy.TinyIoc.TinyIoCRegistrationException: Cannot convert current registration of Nancy.TinyIoc.TinyIoCContainer+InstanceFactory to singleton – ulu Dec 20 '16 at 10:43
  • 1
    Turned out that factory methods are not compatible with Singleton lifecycle. A known TinyIoC limitation. – ulu Dec 20 '16 at 10:49
  • Ah. Good to know. – David Osborne Dec 20 '16 at 12:01
0

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

pipelines.AfterRequest += (ctx) => {
    //close the connection
    container.Resolve<OrmLiteConnection>().Dispose();
};
ulu
  • 5,872
  • 4
  • 42
  • 51
  • Is this correct? When I try this, it constructs a new instance (in my case, a DbContext), then disposes it right away. – Tom May 05 '17 at 14:00
  • I've registered it as a singleton in ConfigureRequestContainer. – ulu May 06 '17 at 06:37