views:

78

answers:

2

I have a singleton service with a dependency on a service with a request scoped lifecycle.

If I allow the container to inject the request scoped service when I first get the singleton it will be fine for the current request but will be disposed of in any subsequent request.

Does this mean I have to use the dependency container to create the request scoped service within the singleton?

A: 

I would ask if your object absolutely has to be a singleton. If it doesn't have to be a singleton, then don't make it a singleton and rely on your container to construct it. The problem you are having is because dependency injection relies on inversion of control, and singletons typically construct themselves.

Many containers will take responsibility for the lifecycle of the objects they construct. If yours does, you might be able to instruct it to only use a single instance of your object. If I'm reading your question correctly, however, you really need a new instance of the objectwith each request since the state (the service) is different per request.

In short, use singleton as a last resort because it causes the type of problem that you're experiencing now. If you are locked in to that pattern, consider not injecting the service but passing it as a parameter. If you introduce it to state, you'll have concurrency problems with multiple simultaneous requests needing different instances of the service.

Michael Meadows
+1  A: 

I wouldn't recommend injecting the container itself in your singleton service. Instead:

  • abstract the creation of your request-scoped service behind a factory, and inject the factory, or
  • change your singleton's scope and make it request-scoped. This shouldn't be a problem unless the instantiation of the service is expensive.
Mauricio Scheffer