Skip to main content
Remy DI - Dependency Injection for Go
GitHub Go Docs Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

LazySingleton

LazySingleton creates a single instance of the service, but only when it’s first requested. This is useful for expensive objects that may not always be needed.

Key Points:

  • πŸš€ Lazy services are loaded on first invocation
  • 🐎 Lazy service invocation is protected against concurrent loading
  • πŸ’Ύ The instance is cached after first creation

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
	"database/sql"

	"github.com/wrapped-owls/goremy-di/remy"
)

func init() {
	remy.Register(
		nil,
		remy.LazySingleton(
			func(retriever remy.DependencyRetriever) (*sql.DB, error) {
				// This will only be called when the database is first requested
				return sql.Open("sqlite3", "file:locked.sqlite?cache=shared&mode=memory")
			},
		),
	)
}

You can also use the convenience function:

1
2
3
4
5
6
remy.RegisterLazySingleton(
    nil,
    func (retriever remy.DependencyRetriever) (*sql.DB, error) {
        return sql.Open("sqlite3", "file:locked.sqlite?cache=shared&mode=memory")
    },
)

The database connection will only be established when Get[*sql.DB] is called for the first time.