Simple Dependency Injection

Back

2023-05-16

All we need is a type and a function:

		
type FactoryFunc[T any] func() T

func Factory[T any](v T) FactoryFunc[T] {
	return func() T {
		return v
	}
}
		
        

Then we can do this:

		
type App struct {
...
    Repo Factory[Repo]
    SomeApiClient Factory[ApiClient]
...
}
...
app := App{
    Repo: func() Repo { return repo },
    SomeApiClient: func() ApiClient { return apiclient.New() },
}

app.Repo().YAAAAS()

app.SomeApiClient().WIIIII()

        
        
}