Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inject struct fields #2

Closed
zeromake opened this issue Mar 27, 2020 · 1 comment · Fixed by #6
Closed

Inject struct fields #2

zeromake opened this issue Mar 27, 2020 · 1 comment · Fixed by #6
Labels
enhancement New feature or request

Comments

@zeromake
Copy link

my project full of injection functions like this

type Controller struct {
	user   types.UserService
	cfg    *config.Config
	friend types.FriendService
}

func NewController(cfg *config.Config, user types.UserService, friend types.FriendService) *Controller {
	return &Controller{
		user:   user,
		cfg:    cfg,
		friend: friend,
	}
}

I hope to support tag auto inject E.g: di.Parameter

type Controller struct {
	User   types.UserService   `di:""` // has `di` tag auto inject, di tag with name
	Cfg    *config.Config      `di:""`
	Friend types.FriendService `di:""`
}

func NewController() *Controller {
	return &Controller{}
}

Here is my simple implementation

diff --git a/parameter.go b/parameter.go
index acfe8e0..58a504b 100644
--- a/parameter.go
+++ b/parameter.go
@@ -2,6 +2,8 @@ package di
 
 import (
 	"reflect"
+	"strings"
+	"unsafe"
 )
 
 // isEmbedParameter
@@ -61,9 +63,63 @@ func (p parameter) ResolveValue(c *Container) (reflect.Value, error) {
 	if cleanup != nil {
 		c.cleanups = append(c.cleanups, cleanup)
 	}
+	// inject struct
+	err = p.ResolveProperty(c, value)
+	if err != nil {
+		return reflect.Value{}, err
+	}
 	return value, nil
 }
 
+const (
+	flagRO = 0b1100000
+)
+
+func ValuePatch(v reflect.Value) reflect.Value {
+	rv := reflect.ValueOf(&v)
+	flag := rv.Elem().FieldByName("flag")
+	ptrFlag := (*uintptr)(unsafe.Pointer(flag.UnsafeAddr()))
+	*ptrFlag = *ptrFlag &^ flagRO
+	return v
+}
+
+func (p parameter) ResolveProperty(c *Container, value reflect.Value) (err error) {
+	value = reflect.Indirect(value)
+	if value.Kind() != reflect.Struct {
+		return nil
+	}
+	vType := value.Type()
+	for i := 0; i < value.NumField(); i++ {
+		fieldType := vType.Field(i)
+		field := ValuePatch(value.Field(i))
+		tag, ok := fieldType.Tag.Lookup("di")
+		if ok {
+			var optional = false
+			var name string
+			tags := strings.Split(tag, ",")
+			for _, t := range tags {
+				t = strings.Trim(t, " ")
+				if t == "optional" {
+					optional = true
+					continue
+				}
+				name = t
+			}
+			pp := parameter{
+				name:     name,
+				typ:      fieldType.Type,
+				optional: optional,
+			}
+			param, err := pp.ResolveValue(c)
+			if err != nil {
+				return err
+			}
+			field.Set(param)
+		}
+	}
+	return nil
+}
+
 // internalParameter
 type internalParameter interface {
 	isDependencyInjectionParameter()

ValuePatch is private field set patch func, not necessary

@defval
Copy link
Owner

defval commented Mar 27, 2020

@zeromake Hi! Thank you for your interest.

I understand your problem. But I wouldn't want the code to be unable to be used without a container. This approach creates a direct connection between the container and the package that contains such a constructor. And if you use the constructor without a container, you will get a non-working code. I would like to avoid this.
On the other hand, this is an optional feature. This does not change the normal workflow. In general, it can be merged.

As an alternative, how do you look to introduce the di.ProvideValue() with di.ResolvePublicFields() provide option (need to think about naming):

di.ProvideValue(&Controller{}, di.ResolvePublicFields()),

If di.ResolvePublicFields() is specified, the container will bypass the public properties of the type and inject dependencies in them without tags.

@defval defval changed the title new features: support struct property auto inject Inject struct fields Mar 27, 2020
@defval defval added the enhancement New feature or request label Apr 3, 2020
@defval defval closed this as completed in #6 Apr 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants