Skip to content
John Wells edited this page Sep 4, 2018 · 5 revisions

Dependency Injection for GO!

Welcome to Dargo, a dependency injection library for Go. Firstly, about the name: Dargo stands for "Dynamic Application Registry for GO." While, that name does fit, since there is, in fact, a dynamic in-memory service registry at the heart of Dargo, in truth, it's the name of my dog. And I made the acronym sort-of kind-of fit. So sue me. No, not really. I can't afford lawyers.

I am also the technical lead for the java hk2 project, which is a dependency injection system for Java used as the basis for several projects, like Jersey, GlassFish, WebLogic and more. Any similarities between the hk2 and Dargo API are purely intended. However, Go is a different language with different strengths and weaknesses and I hope that the Dargo API is a more go-friendly language.

The biggest difference between hk2 and Dargo is that in hk2 services are normally categorized by their Java type. The original versions of Dargo also had this, but it doesn' work very well in Go, because in Go no-one uses the reflect.Type of their services in day-to-day programming. So instead Dargo services are more simply categorized by names. These names are more complex, as they have a namespace component, but they are also a lot more natural to use in Go.

The main idea behind the dependency injection is to use the tag elements of structures to say which services to inject. For example, if you have a Service A which depends on Service B and C, and B also depends on D, you might define your structures for those services like this:

type ServiceA struct {
  B *ServiceB `inject:"BName"`
  C *ServiceC `inject:"CName"`
}

type ServiceB struct {
  // whatever is here
}

type ServiceC struct {
  D *ServiceD `inject:"DName"`
}

Dargo services are normally lazy (although there is an Immediate scope whose services are NOT, in fact, lazy). They will not get created until someone looks them up or tries to inject them. The central service registry of "Application Registry" fame is not in fact a registry of services themselves, but of service descriptions.

Normally, when you create this registry at the start of your program you bind service descriptions

Clone this wiki locally