PageRenderTime 9ms CodeModel.GetById 1ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/app/conf/context.go

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