3

I'm not sure the specific implementation is important here but for completeness I'm using Autofac as my dependency injection container for a new application.

All my repositories depend on a DbContext (unit of work) which I have used the MVC3 integration library to configure as InstancePerHttpRequest() so that the unit of work is shared between repositories for each request.

I've looked at some applications that use Autofac and I have noticed that they're setting the lifetime of their repositories as SingleInstance() (singleton). Is this correct?

The reason I ask is that I can understand that we don't really need multiple repository classes but if we're creating a single instance of a repository then that surely means that there is only one reference to a DbContext. In my repository implementation it accesses the DbContext as a class member e.g. _dbContext.Set<T> blah....

So _dbContext must have a reference to some object in memory. How is it possible for two separate requests to come along, have a unique DbContext but share the same repository?

Have I missed something to do with the way DI works?

jgauffin
  • 99,844
  • 45
  • 235
  • 372
Tom Miller
  • 435
  • 8
  • 18
  • 1
    It mostly sounds like a misconfiguration of lifetimes, because I can certainly understand why you ask. However, in theory, it's possible to make it work using this trick: http://stackoverflow.com/questions/4648318/dependency-injection-new-instance-required-in-several-of-a-classes-methods/4650050#4650050 – Mark Seemann Mar 09 '12 at 15:26

1 Answers1

2

You haven't missed anything - SingleInstance() is almost certainly the wrong choice for repositories in your scenario.

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101