Duración del repositorio de inyección de dependencia

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?

preguntado el 09 de marzo de 12 a las 14:03

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: stackoverflow.com/questions/4648318/… -

1 Respuestas

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

respondido 09 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.