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

Factory

Factory creates a new instance every time the service is requested. This is useful for services that should not be shared or need fresh state on each use.

Key Points:

  • ๐Ÿ”„ New instance created on each request
  • ๐Ÿšซ No caching or reuse
  • ๐Ÿงต Safe for concurrent use (each call gets its own instance)

Example

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

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

type RequestID string

func init() {
	remy.Register(
		nil,
		remy.Factory(
			func(retriever remy.DependencyRetriever) (RequestID, error) {
				// Each call will generate a new unique request ID
				return RequestID(generateUniqueID()), nil
			},
		),
	)
}

You can also use the convenience function:

1
2
3
4
5
6
remy.RegisterFactory(
    nil,
    func (retriever remy.DependencyRetriever) (RequestID, error) {
        return RequestID(generateUniqueID()), nil
    },
)