container icon indicating copy to clipboard operation
container copied to clipboard

Lazy singleton construction

Open Place1 opened this issue 2 years ago • 7 comments

This PR makes singleton construction lazy. It also adds a lock to each container binding so that multiple goroutines can safely work with the container at the same time.

This feature is very helpful if you have multiple programs/entrypoints that share the same container but only use a subset of the dependencies.

In my use-case I have a server and cli application that share the same container; there are many shared dependencies but not everything is used by both programs. For example the TLS configuration used by the server isn't used by the cli application and attempting to resolve it will fail because the certificates won't be available.

With this PR the problem is solved because only the dependencies (bindings) that are requested are constructed; if the cli app never requests the TLS configuration then it's resolver is never executed.

Place1 avatar Apr 26 '22 03:04 Place1

I'm happy to write tests if this is something you'd like to merge.

Place1 avatar Apr 26 '22 03:04 Place1

Imho it's a good thing, but it should be an option, not the default choice.

Cililing avatar Apr 28 '22 12:04 Cililing

I agree with @Cililing

miladrahimi avatar Apr 28 '22 12:04 miladrahimi

Yeah that makes sense. Any idea about the best way to support that configuration?

Place1 avatar Apr 28 '22 12:04 Place1

How about new methods like lazySingleton and lazyNamedSingleton?

miladrahimi avatar Apr 28 '22 12:04 miladrahimi

Yeah that sounds reasonable

  • LazySingleton
  • LazyNamedSingleton
  • MustLazySingleton
  • MustLazyNamedSingleton

Place1 avatar Apr 28 '22 12:04 Place1

@Place1 any updates? This is a feature I'd like to use myself.

wirecat avatar Jul 19 '22 23:07 wirecat