예제 #1
0
// RegisterTypes registers all types that have been defined in the file "config/types.yml"
//
// DO NOT EDIT THIS FILE: it has been generated by goldigen v0.9.9.
// It is however good practice to put this file under version control.
// See https://github.com/fgrosse/goldi for what is going on here.
func RegisterTypes(types goldi.TypeRegistry) {
	types.RegisterAll(map[string]goldi.TypeFactory{
		"composed_endpoint":             goldi.NewType(handler.Composed, "@my_controller::OuterHandlerAction", "@my_controller::SecondHandlerAction", "@my_controller::FancyAction"),
		"container_aware_endpoint":      goldi.NewFuncReferenceType("my_container_aware_controller", "SomeAction"),
		"controller_endpoint":           goldi.NewFuncReferenceType("my_controller", "FancyAction"),
		"custom_error_handler":          goldi.NewStructType(new(lib.MyErrorHandler)),
		"error_endpoint":                goldi.NewFuncReferenceType("my_controller", "ErrorAction"),
		"greet_user_endpoint":           goldi.NewFuncType(endpoints.GreetUserEndpoint),
		"homepage_endpoint":             goldi.NewFuncType(endpoints.HomepageEndpoint),
		"kernel.http_handler":           goldi.NewType(handler.MiddleWareAdapter, "@servo.routing.router", "@my_app.error_handler", "@my_app.logging_adapter"),
		"my_app.error_handler":          goldi.NewType(middleware.ErrorHandlingAdapter, "@custom_error_handler::HandleEndpointError"),
		"my_app.logging_adapter":        goldi.NewType(middleware.LoggingAdapter, "@my_logger"),
		"my_container_aware_controller": goldi.NewStructType(new(endpoints.ContainerAwareController), "@container"),
		"my_controller":                 goldi.NewStructType(new(endpoints.FancyController), "@my_service_client"),
		"my_logger":                     goldi.NewProxyType("logger_provider", "GetLogger", "my_app"),
		"my_service_client":             goldi.NewType(lib.NewMockServiceClient, "%my_app.some_parameter%"),
	})
}
예제 #2
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)
}
예제 #3
0
func ExampleNewFuncType() {
	container := goldi.NewContainer(goldi.NewTypeRegistry(), map[string]interface{}{})

	// define the type
	container.Register("my_func", goldi.NewFuncType(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "test" {
			w.WriteHeader(http.StatusAccepted)
		}
	}))

	// generate it
	result, err := container.Get("my_func")
	if err != nil {
		return
	}

	// call it
	f := result.(func(name string, age int) (bool, error))
	ok, err := f("foo", 42)
	if ok != true || err != nil {
		panic("!!!")
	}
}
예제 #4
0
	// call it
	f := result.(func(name string, age int) (bool, error))
	ok, err := f("foo", 42)
	if ok != true || err != nil {
		panic("!!!")
	}
}

// ExampleNewFuncType_ prevents godoc from printing the whole content of this file as example
func ExampleNewFuncType_() {}

var _ = Describe("funcType", func() {
	It("should implement the TypeFactory interface", func() {
		var factory goldi.TypeFactory
		factory = goldi.NewFuncType(SomeFunctionForFuncTypeTest)

		// if this compiles the test passes (next expectation only to make compiler happy)
		Expect(factory).NotTo(BeNil())
	})

	Describe("goldi.NewFuncType()", func() {
		Context("with invalid argument", func() {
			It("should return an invalid type if the argument is no function", func() {
				Expect(goldi.IsValid(goldi.NewFuncType(42))).To(BeFalse())
			})
		})

		Context("with argument beeing a function", func() {
			It("should create the type", func() {
				typeDef := goldi.NewFuncType(SomeFunctionForFuncTypeTest)