golang使用wire依赖注入时,解决注入时类型相同时生成wire_gen.go文件时报错:ProviderSet has multiple bindings for xx/xx/xxx.go

1 篇文章 0 订阅

问题:类似以下这种创建实例的方式,在ProviderSet中添加各个需要注入的实例后,由于injector的函数中,不允许出现重复的参数类型,否则wire将无法区分这些相同的参数类型,因此编译时会报错。

func NewCertificateUseCase(repo CertificateRepo, huawei HuaweiCertificateRepo,
	ios CertificateRepo,
	iosP8 CertificateRepo,
	meizu CertificateRepo,
	miAndGoogle CertificateRepo,
	oppo CertificateRepo,
	vivo CertificateRepo,
	logger log.Logger) *CertificateUseCase {
	return &CertificateUseCase{repo,
		huawei,
		ios,
		iosP8,
		meizu,
		miAndGoogle,
		oppo,
		vivo,
		log.NewHelper(logger)}
}
var ProviderSet = wire.NewSet(NewData, NewAppRepo, NewImUserStaticRepo, NewUserRepo,
	NewParentCertificateRepo, NewIosP8Certificate, NewIosPCertificate, NewAndHuaweiCertificate,
	NewAndMeizuCertificate, NewMiAndGoogle, NewAndOppoCertificate, NewAndVivoCertificate, NewClientAppRepo)

解决方案:通过创建新的类型来避免此问题。如下:

因为HuaweiCertificateRepo和CertificateRepo的接口是完成相同的,实现了HuaweiCertificateRepo接口,也就实现了CertificateRepo。因此GetCerInter的返回值是CertificateRepo

type HuaweiCertificateRepo CertificateRepo
type IosCertificateRepo CertificateRepo
type IosP8CertificateRepo CertificateRepo
type MeizuCertificateRepo CertificateRepo
type MiAndGoogleCertificateRepo CertificateRepo
type OppoCertificateRepo CertificateRepo
type VivoCertificateRepo CertificateRepo

type CertificateUseCase struct {
	repo        CertificateRepo
	huawei      HuaweiCertificateRepo
	ios         IosCertificateRepo
	iosP8       IosP8CertificateRepo
	meizu       MeizuCertificateRepo
	miAndGoogle MiAndGoogleCertificateRepo
	oppo        OppoCertificateRepo
	vivo        VivoCertificateRepo
	log         *log.Helper
}

func NewCertificateUseCase(repo CertificateRepo, huawei HuaweiCertificateRepo,
	ios IosCertificateRepo,
	iosP8 IosP8CertificateRepo,
	meizu MeizuCertificateRepo,
	miAndGoogle MiAndGoogleCertificateRepo,
	oppo OppoCertificateRepo,
	vivo VivoCertificateRepo,
	logger log.Logger) *CertificateUseCase {
	return &CertificateUseCase{repo,
		huawei,
		ios,
		iosP8,
		meizu,
		miAndGoogle,
		oppo,
		vivo,
		log.NewHelper(logger)}
}

func (cuc *CertificateUseCase) GetCerInter(Type string) CertificateRepo {
	switch Type {
	case constant.IOS_P8:
		return cuc.iosP8
......
	case constant.VivoAnd:
		return cuc.vivo
	case constant.OppoAnd:
		return cuc.oppo
	default:
		return nil
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值