dofactory

package module
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

README

Convert Factory Function into github.com/samber/do/v2.Provider

📦 A utility for converting factory function into do.Provider for integration with the samber/do/v2 DI.

📌 Installation

go get github.com/d-enk/dofactory

🚀 Usage

1. Define a Factory Function

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}
}
2. Convert the Factory into a Provider

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

🎯 How It Works

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.

🔧 Supported Factory Function Signatures

func(A, B, ...) (T, error)
func(A, B, ...) T

❗Variadic Functions not supported

📜 License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ToProvider

func ToProvider[T any](factory Factory[T]) do.Provider[T]

ToProvider converts a Factory function into a do.Provider. The returned provider can be used in a dependency injection container to resolve and invoke the factory function, creating instances of type T.

Example:

factory := func() *Type { return &Type{} }
provider := dofactory.ToProvider(factory)
injector := do.New()
do.Provide(injector, provider)
typeInstance := do.MustInvoke[*Type](injector)

Parameters:

  • factory: The factory function that creates instances of type T.

Returns:

  • A do.Provider that invokes the factory function to create instances of T.

Types

type Factory

type Factory[T any] any // func(...) (T[, error])

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL