google / wire

Compile-time Dependency Injection for Go

Repository from Github https://github.comgoogle/wireRepository from Github https://github.comgoogle/wire

how to reusable wire set

anyufly opened this issue · comments

we have those types and interfaces below

example.go

type A struct{
    ...  // some fields
}

type B struct{
    ....  // some fields
}

type Session struct{
    ... // some fields
}

func NewSession() *Session {
    return &Session{
      ...
    }
}

func (s *Session) doGetA() *A {
    ... // some operate
}

func (s *Session) doGetB() *B {
    ... // some operate
}

type AB struct{
      A *A
      B *B
}

type IADao interface {
    GetA() *A
}

type IBDao interface {
    GetB() *B
}

type ADao struct {
    session *Session
}

func NewADao(session *Session) *ADao {
    return &ADao {
        session: session
    }
}

func (dao *ADao) GetA() *A{
   return dao.session.doGetA()
}

type BDao struct {
    session *Session
}

func NewBDao(session *Session) *BDao {
    return &BDao {
        session: session
    }
}

func (dao *BDao) GetB() *B{
    return dao.session.doGetB()
}

type AService struct {
    aDao IADao
    bDao IBDao
}

func NewAService(aDao IADao, bDao IBDao) *AService {
    return &AService{
        aDao: aDao,
        bDao: bDao
    }
}

func (s *AService) GetAB() *AB {
    a  := s.aDao.GetA()
    b := s.bDao.Get(B)
    return &AB{
        A:a,
        B:b
    }
}

type BService struct {
    bDao IBDao
}

func NewBService(bDao) *BService {
    return &BService {
        bDao: bDao
    }
}

func (s *BService) GetB() *B {
    return  s.bDao.GetB()
}

now i want to inject AService and BService, with wire config file below

wire_config.go

var aDaoWireSet = wire.NewSet(wire.Bind(new(IADao), new(*ADao)), NewADao, NewSession)
var bDaoWireSet = wire.NewSet(wire.Bind(new(IBDao), new(*BDao)), NewBDao, NewSession)

var aServiceWireSet = wire.NewSet(aDaoWireSet, bDaoWireSet, NewAService)
var bServiceWireSet = wire.NewSet(bDaoWireSet, NewBService)

func AService() *Aservice {
   wire.Build(aServiceWireSet)
    return nil
}

func BService() *BService {
    wire.Build(aServiceWireSet)
    return nil
}

when i generated the wire_gen.go, encounted an error means that it has muilty dependecy define for the *Session type, it was easy to understand, but if there have some way to make the aDaoWireSet and bDaoWireSet reusable to inject an AService object depend on the same *Session?

same problem