Nacelle

Go service framework
/

How to inject services recursively into struct fields

This guide describes a feature of the github.com/go-nacelle/service package. See related documentation.


It should be noted that injection does not work recursively. The procedure does not look into the values of non-anonymous fields. If this behavior is needed, it can be performed during a post-injection hook. The following example demonstrates this behavior.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
type RecursiveInjectionConsumer struct {
	Services *service.ServiceContainer `service:"services"`
	FieldA   *A
	FieldB   *B
	FieldC   *C
}

func (c *RecursiveInjectionConsumer) PostInject() error {
	fields := []interface{}{
		c.FieldA,
		c.FieldB,
		c.FieldC,
	}

	for _, field := range fields {
		if err := c.Services.Inject(field); err != nil {
			return err
		}
	}

	return nil
}