defval / di

🛠 A full-featured dependency injection container for go programming language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Provide values via custom string types

matdurand opened this issue · comments

Hey,

Maybe a bit related to #39 but on the Provide side of things.

It seems that I cannot do this, why? Seems like a better way than using tags to identify strings.

package main

import (
	"github.com/defval/di"
)

type ProjectName string

func main() {
	_, err := di.New(
		di.ProvideValue("project1", di.As(new(ProjectName))),
	)
	if err != nil {
		panic(err)
	}
}

I'm getting *main.ProjectName: not a pointer to interface

I was able to make it work like this, but it's lot more verbose

type InterfaceString struct {
	Value string
}

func (i InterfaceString) String() string {
	return i.Value
}

type ProjectName interface {
	String() string
}

func run(p ProjectName) {
	fmt.Println(p.String())
}

func main() {
	di, err := di.New(
		di.ProvideValue(InterfaceString{Value: "project1"}, di.As(new(ProjectName))),
	)
	if err != nil {
		panic(err)
	}

	err = di.Invoke(run)
	if err != nil {
		panic(err)
	}
}

I figured out how to do it with ProvideValue. I created a PR to explain this in the documentation.
#52