dingo icon indicating copy to clipboard operation
dingo copied to clipboard

Move dic.C into another file inside the output that survives between generations

Open SeanLatimer opened this issue 3 years ago • 3 comments

It would be nice to be able to change dic.C inside the package without changes being clobbered when a new container is generated

SeanLatimer avatar May 24 '22 19:05 SeanLatimer

Hello, if I understand want you are doing, you are modifying the generated file where the dic.C function is defined. What you should do instead is redefining the function in your own code, for example where the container is created.

dic.C = func(i interface{}) *Container {
 // find and return the container
}
ctn, err := dic.NewContainer()

sarulabs avatar May 28 '22 11:05 sarulabs

This is what I am currently doing but two issues I have with it are A) it does not feel clean, and B) it's something that does not need to be able to be changed at runtime, so it's an unnecessarily modifiable piece of code

SeanLatimer avatar May 28 '22 19:05 SeanLatimer

I don't think it's a good idea to keep some files in the output directory.

I guess what could be done instead would be to:

  • have the method in its own file
  • give the possibility to use your own template files

That means that you would have to write something like this.

var MyTemplate = `
<<< define "base" ->>>
	package <<< .PkgName >>>

	import (
		"net/http"
		"github.com/sarulabs/dingo/v4"
	)

	// C retrieves a Container from an interface.
	// The function panics if the Container can not be retrieved.
	//
	// The interface can be :
	// - a *Container
	// - an *http.Request containing a *Container in its context.Context
	//   for the dingo.ContainerKey("dingo") key.
	//
	// The function can be changed to match the needs of your application.
	var C = func(i interface{}) *Container {
		if c, ok := i.(*Container); ok {
			return c
		}
		r, ok := i.(*http.Request)
		if !ok {
			panic("could not get the container with dic.C()")
		}
		c, ok := r.Context().Value(dingo.ContainerKey("dingo")).(*Container)
		if !ok {
			panic("could not get the container from the given *http.Request in dic.C()")
		}
		return c
	}
<<< end >>>
`

sarulabs avatar May 30 '22 19:05 sarulabs