-1

Given the following code from my Configure method:

OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("Oracle:FEConnection"), OracleOrmLiteDialectProvider.Instance);

container.Register<IDbConnectionFactory>(dbFactory)).ReusedWithin(ReuseScope.Request); // <== this does NOT work

// But these work
container.Register<IPreprocessorRepository>(c => new CachedPreprocessorRepository(dbFactory, c.Resolve<ICacheClient>())).ReusedWithin(ReuseScope.Default);
container.Register<IPreprocessor>(c => new DirectApiPreprocessor(c.Resolve<IPreprocessorRepository>(), c.Resolve<IValidator<LeadInformation>>())).ReusedWithin(ReuseScope.Default);

How can I make sure that the dbFactory instanciated is used in other registrations will per request?

Thank you, Stephen

Stephen Patten
  • 6,333
  • 10
  • 50
  • 84

1 Answers1

1

You can't change the scope of this:

container.Register<IDbConnectionFactory>(dbFactory)
    .ReusedWithin(ReuseScope.Request);

Because you're only passing in an instance of an object, and not a factory function that the IOC would need to be able to instantiate instances of the object itself. All the IOC can do in this case is return the instance, making it a singleton.

To be able to change the scope you would need to register a delegate that can create an instance, i.e:

container.Register<IDbConnectionFactory>(c => 
      new OrmLiteConnectionFactory(...))
    .ReusedWithin(ReuseScope.Request);

But you never want to do this with any connection or client factories like IDbConnectionFactory or IRedisClientsManager since they're designed to be used as singletons.

i.e. They're thread-safe singleton factories used to create single client/connection instances:

using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
    //...
}

using (var redis = container.Resolve<IRedisClientsManager>().GetClient())
{
    //...
}
mythz
  • 141,670
  • 29
  • 246
  • 390
  • @StephenPatten ok I've added the approach I would take: http://stackoverflow.com/a/26796083/85785 – mythz Nov 07 '14 at 07:22