Your Question
A hook is a method on a model that receives a DB object (and a pointer to itself). This limits possible hook dependencies to:
- Fields/state on the model: this breaks away from using models as PODs.
DBcontext: this is fine for tracing, but not intended for dependencies.- Using some global singleton variables: this is problematic for tests, needs mutex for threads etc.
In my actual use case, I have some request-id tracing stuff which works fine as context, but I also have an eventbus instance that I'm trying to move away from global singleton (3.) with context, but this is also being quite problematic.
Is there a "proper" way to inject dependencies into hooks, or some recommendation?
The document you expected this should be explained
https://gorm.io/docs/hooks.html
Expected answer
Preferred choice, another option that I didn't know, or reframing the problem itself. Thank you!
Comment From: a631807682
Do you need db.Statement.Settings?
https://gorm.io/docs/settings.html#content-inner
Comment From: benjajaja
@a631807682 yes exactly something like that. Do Settings get propagated into new .Sessions and transactions?
Comment From: a631807682
It depends on how you use it
tx1 := DB.Set("test", 123)
v, _ := DB.Get("test") // nil
v1, _ := tx1.Get("test") // 123
Here it is described whether to copy settings or not https://github.com/go-gorm/gorm/blob/master/gorm.go#L366
Comment From: benjajaja
Aha, it looks like it copies the settings then. Great, thanks a lot!