Ejemplo n.º 1
0
func Example() {
	// create a new container when your application loads
	registry := goldi.NewTypeRegistry()
	config := map[string]interface{}{
		"some_parameter": "Hello World",
		"timeout":        42.7,
	}
	container := goldi.NewContainer(registry, config)

	// now define the types you want to build using the di container
	// you can use simple structs
	container.RegisterType("logger", &SimpleLogger{})
	container.RegisterType("api.geo.client", new(GeoClient), "http://example.com/geo:1234")

	// you can also use factory functions and parameters
	container.RegisterType("acme_corp.mailer", NewAwesomeMailer, "first argument", "%some_parameter%")

	// dynamic or static parameters and references to other services can be used as arguments
	container.RegisterType("renderer", NewRenderer, "@logger")

	// closures and functions are also possible
	container.Register("http_handler", goldi.NewFuncType(func(w http.ResponseWriter, r *http.Request) {
		// do amazing stuff
	}))

	// once you are done registering all your types you should probably validate the container
	validator := validation.NewContainerValidator()
	validator.MustValidate(container) // will panic, use validator.Validate to get the error

	// whoever has access to the container can request these types now
	logger := container.MustGet("logger").(LoggerInterface)
	logger.DoStuff("...")

	// in the tests you might want to exchange the registered types with mocks or other implementations
	container.RegisterType("logger", NewNullLogger)

	// if you already have an instance you want to be used you can inject it directly
	myLogger := NewNullLogger()
	container.InjectInstance("logger", myLogger)
}
Ejemplo n.º 2
0
	"github.com/fgrosse/goldi/validation"
)

var _ = Describe("ContainerValidator", func() {
	var (
		registry  goldi.TypeRegistry
		config    map[string]interface{}
		container *goldi.Container
		validator *validation.ContainerValidator
	)

	BeforeEach(func() {
		registry = goldi.NewTypeRegistry()
		config = map[string]interface{}{}
		container = goldi.NewContainer(registry, config)
		validator = validation.NewContainerValidator()
	})

	It("should return an error if an invalid type was registered", func() {
		registry.Register("main_type", goldi.NewFuncReferenceType("not_existent", "type"))

		Expect(validator.Validate(container)).NotTo(Succeed())
	})

	It("should return an error when parameter has not been set", func() {
		typeDef := goldi.NewType(NewMockTypeWithArgs, "hello world", "%param%")
		registry.Register("main_type", typeDef)

		Expect(validator.Validate(container)).NotTo(Succeed())
	})