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
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.