📦 A utility for converting factory function into do.Provider
for integration with the samber/do/v2
DI.
go get github.com/d-enk/dofactory
A factory function is a function that creates instances of an object:
package main
import (
"fmt"
"github.com/samber/do/v2"
"github.com/d-enk/dofactory"
)
type Service struct {
Name string
}
func NewService(name string) *Service {
return &Service{Name: name}
}
With dofactory.ToProvider
, you can easily register a factory as a provider in the DI container:
func main() {
injector := do.New()
// Provide service name
do.ProvideValue(injector, "MyService")
// Convert factory to provider
factoryProvider := dofactory.ToProvider[*Service](NewService)
// Register provider
do.Provide[*Service](injector, factoryProvider)
// Retrieve the instance from the container
service := do.MustInvoke[*Service](injector)
fmt.Println(service.Name) // Output: MyService
}
More examples
The dofactory.ToProvider
function takes a factory function (e.g., func() *Service
) and converts it into a do.Provider[T]
.
The provider automatically resolves dependencies via the do.Injector
DI container.
func(A, B, ...) (T, error)
func(A, B, ...) T
❗Variadic Functions not supported
Implicit type conversion when resolving factory functions. For example:
// Converting `uint32` to `int`
dofactory.ToProvider[int](func() uint32 { return 0 })
// Converting `[]byte` to `string`
dofactory.ToProvider[string](func() []byte { return nil })
// Converting `*bytes.Reader` to `io.Reader`
dofactory.ToProvider[io.Reader](func() *bytes.Reader { return nil })
This project is licensed under the Apache License 2.0. See the LICENSE file for details.