Using IoC, can objects with a temporary lifetime be introduced into Singleton?

We have an ASP.NET MVC application using IoC to inject service references into controllers and repository links into Services.

Controllers must have a Lifetime Transient, as they must be created for each request. If the entire IoC stack is updated for each request, this becomes a bit overhead. We have more dependencies than we would like, and one option would be to have more controllers, each of which has fewer dependencies on the stack. But, leaving that aside for the moment, my question is that if an object that is injected as a singleton has dependencies having a temporary lifetime, will these dependencies be essentially considered as singleton due to the fact that they belong to Singleton ?

In particular, if we have the following

RepositoryA (should be temporary because the current project enters the user context in the constructor) ServiceA (singleton) Controller (transient)

is created in this way:

public ServiceA(IRepositoryA repo) {} public ControllerA(IServiceA service) {} 

Will RepositoryA essentially be instantiated once because ServiceA is instantiated?

I'm 99% sure that yes, but I just wanted to confirm the amount of refactoring I have to do here.

In addition, if the services and repositories did not have any instance variables depending on the user and the request, as a design approach, is there any reason not to use the Singleton lifetime for them?

+6
source share
1 answer

if an object that is introduced as a singleton has dependencies that have a temporary lifetime, will these dependencies be considered substantially as single individuals because they belonged to Singleton?

It is right. Since such a component belongs to its dependencies (by storing their link in a private field), these dependencies will live as long as the component itself does. In other words, their lifetime is implicitly advancing to the lifetime of the component (if their lifetime is shorter).

If you have this, your DI configuration is certainly incorrect, and sooner or later this error will appear. Probably only in production and almost never on your dev: -S machine.

In general, all components managed by the container should depend only on abstractions whose service life is equal to or longer than that of the component itself.

Some infrastructures even have analysis services to detect such configuration errors. However, you must be very careful when connecting all the dependencies. In general, it would be safer to configure components as transient when possible, since transitional components can contain dependencies of any lifestyle. Having many transition objects is usually not a performance issue. Building a fairly large object graph for each web request will usually be fast enough (otherwise try switching to a higher throughput DI infrastructure ).

+4
source

All Articles