/app/conf/context.go

http://github.com/sut-go/gon · Go · 62 lines · 51 code · 11 blank · 0 comment · 2 complexity · a10c6809ebc903bd331840d8b4ffe417 MD5 · raw file

  1. package bean
  2. import "launchpad.net/mgo"
  3. import "app/domain/book"
  4. type AppContext struct {
  5. registry map[string]func()interface{}
  6. }
  7. var DefaultAppContext = NewAppContext()
  8. func NewAppContext() *AppContext {
  9. return &AppContext{make(map[string]func()interface{})}
  10. }
  11. func Registry() map[string]func()interface{} {
  12. return DefaultAppContext.registry
  13. }
  14. func GetBean(name string) interface{} {
  15. return DefaultAppContext.GetBean(name)
  16. }
  17. func (a *AppContext) GetBean(name string) interface{} {
  18. return a.registry[name]()
  19. }
  20. type Context struct {
  21. name string
  22. function func()interface{}
  23. reply chan int
  24. }
  25. var ch chan *Context = make(chan *Context, 1)
  26. func StartBeanServer() {
  27. go func(){
  28. for {
  29. ctx := <-ch
  30. DefaultAppContext.registry[ctx.name] = ctx.function
  31. ctx.reply<- 1
  32. }
  33. }()
  34. }
  35. func bean(name string, f func()interface{}) {
  36. ctx := &Context{name, f, make(chan int, 1)}
  37. ch<- ctx
  38. <-ctx.reply
  39. }
  40. func Initialize() {
  41. StartBeanServer()
  42. bean("Session", func()interface{} {
  43. session, _ := mgo.Mongo("127.0.0.1")
  44. session.SetMode(mgo.Monotonic, true)
  45. return session
  46. })
  47. bean("BookService", func()interface{}{
  48. bookService := &book.BookService{GetBean("Session").(*mgo.Session)}
  49. return bookService
  50. })
  51. }