Skip to content

Wiring Recipes ​

Connect your Go packages to an App through explicit provider sets. Your package owns constructors. The App's wire package imports them and registers them in the owning set.

Register a constructor directly when it returns the type its consumers need. Add a provider when construction needs configuration, an interface binding, or implementation selection.

Quick Map ​

You builtRegister it inTypical provider
Application serviceapp/wire/inject_services_app.gobilling.NewService
Outbound adapter or gatewayapp/wire/inject_services_app.gobilling.ProvideGateway
Repositoryapp/wire/inject_repositories_app.go when presentreports.NewRepository
HTTP controllerapp/wire/inject_http_controllers_app.gousers.NewController
App commandapp/wire/inject_cmd_app.go and app/commands.goreports.NewReconcileCommand
Job handlerapp/wire/inject_jobs_app.go when jobs are enabledreports.NewGenerateHandler
Scheduleapp/wire/inject_schedules_app.goreports.NewDailySchedule and its AppSchedules entry
Event subscriberapp/wire/inject_subscribers_app.gobilling.NewInvoicePaidSubscriber
Named resource adapterUsually app/wire/inject_services_app.goprovideUploadsDisk

For an additional app, replace app/... with the owning app's app/<name>/....

Use the most specific generated set that owns the surface. If a generated file is not present, the app probably does not have that component enabled.

Generated Resources ​

When a resource has a make command, use it before editing provider sets by hand. The command creates the resource and updates the active App's generated wiring boundaries.

Use the Make Command Reference to create entry points, then wire the services and adapters they consume here.

Service and Adapter ​

Keep the service and adapter constructors in internal/billing/. Add them to the existing appSet in app/wire/inject_services_app.go, preserving its other entries. These illustrative fragments require your own billing operations and consumers. Use your Project's module path for imports.

go
package wire

import (
	"github.com/goforj/wire"

	"myapp/internal/billing"
)

// appSet groups the App-owned service providers.
var appSet = wire.NewSet(
	// existing app providers...
	billing.ProvideGateway,
	billing.NewService,
)

Wire can construct *billing.Service because billing.ProvideGateway provides the *billing.Gateway that billing.NewService receives.

HTTP Controller ​

The controller verification workflow shows the command, files, and injected route registration together.

The controller can depend on an application service already provided by the app service set. If Wire cannot provide that service, add the service constructor to app/wire/inject_services_app.go.

Confirm the controller's routes are registered.

bash
forj route:list

Command ​

The command creation workflow shows the command, generated type, provider, and App command collection together.

Command constructors should receive application services as parameters. They should not create repositories, managers, clients, or services themselves.

Commands also need to be exposed through the generated command collection. See Console Commands for the command-specific registration path.

Named Resource ​

Select a named resource in a provider in app/wire/inject_services_app.go.

go
package wire

import (
	"github.com/goforj/storage"
	"github.com/goforj/wire"

	"myapp/internal/storages"
	"myapp/internal/uploads"
)

// appSet groups the App-owned service providers.
var appSet = wire.NewSet(
	// existing app providers...
	provideUploadsDisk,
	uploads.NewService,
)

// provideUploadsDisk keeps named disk selection in the App graph.
func provideUploadsDisk(manager *storages.Manager) storage.Storage {
	return manager.Uploads()
}

The service receives the selected storage dependency through its constructor.

After Editing ​

Regenerate the graph after changing providers or generated component files.

bash
forj build

forj build refreshes generated code, runs Wire, indexes APIs, and builds the App binary. A successful build checks the graph. Start an App command that reaches the provider to check configuration errors.

Custom Providers ​

Validate Configuration ​

Keep billing HTTP behavior in internal/billing.Gateway. This fragment belongs in internal/billing/gateway.go.

go
// Package billing owns the outbound billing integration.
package billing

import "github.com/goforj/httpclient"

// Gateway owns outbound billing requests for application services.
type Gateway struct {
	http *httpclient.Client
}

// NewGateway receives the client configured for this billing integration.
func NewGateway(client *httpclient.Client) *Gateway {
	return &Gateway{http: client}
}

Resolve configuration once during construction. This provider belongs in internal/billing/provider.go.

go
package billing

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/goforj/httpclient"
)

// gatewayConfig keeps settings private when only the gateway needs them.
type gatewayConfig struct {
	BaseURL string
	Timeout time.Duration
}

// loadGatewayConfig rejects missing endpoints and unbounded request timeouts.
func loadGatewayConfig() (gatewayConfig, error) {
	baseURL := strings.TrimSpace(os.Getenv("BILLING_API_URL"))
	endpoint, err := url.Parse(baseURL)
	if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") {
		return gatewayConfig{}, errors.New("BILLING_API_URL must be an absolute HTTP or HTTPS URL")
	}
	timeoutValue := strings.TrimSpace(os.Getenv("BILLING_TIMEOUT"))
	if timeoutValue == "" {
		timeoutValue = "5s"
	}
	timeout, err := time.ParseDuration(timeoutValue)
	if err != nil || timeout <= 0 {
		return gatewayConfig{}, errors.New("BILLING_TIMEOUT must be a positive duration")
	}
	return gatewayConfig{BaseURL: baseURL, Timeout: timeout}, nil
}

// ProvideGateway validates billing settings before exposing the adapter to consumers.
func ProvideGateway() (*Gateway, error) {
	cfg, err := loadGatewayConfig()
	if err != nil {
		return nil, fmt.Errorf("configure billing gateway: %w", err)
	}
	return NewGateway(httpclient.New(
		httpclient.BaseURL(cfg.BaseURL),
		httpclient.Timeout(cfg.Timeout),
	)), nil
}

The preceding appSet registers billing.ProvideGateway and billing.NewService. Require *billing.Gateway in billing.NewService and connect that service to a controller, command, or other App entry point. Wire calls only providers reachable from the graph root, so an unused provider cannot validate configuration.

Set BILLING_API_URL to the billing endpoint and optionally set BILLING_TIMEOUT, then run forj build and start a command that constructs the App. A missing or malformed endpoint or an invalid timeout stops construction with the setting's name. The provider configures the client without making an outbound request. Verify authentication and reachability through the integration's own health check or request test.

HTTP Client covers the httpclient version, Go requirement, and installation command used by these examples. Keep credentials and request bodies out of errors and diagnostic logs.

Optional Implementations ​

Model an optional integration with a consumer-facing interface and an explicit disabled implementation. A provider returning a billing Gateway interface can produce these outcomes.

ConfigurationProvider result
Billing disabledA NewDisabledGateway() implementation with documented disabled behavior
Billing enabled with valid configurationThe configured HTTP implementation
Billing enabled with invalid configurationA construction error naming the setting

The disabled implementation still satisfies the required constructor parameter. Define whether each operation returns a domain error or deliberately performs no work. Select the disabled branch before requiring endpoint credentials; disabled integrations should not need live-service configuration. Use an interface return type for this design and supply it to each consumer that currently requests *Gateway.

Shared Configuration ​

Keep gatewayConfig private while only ProvideGateway uses it. Promote configuration to a Wire value when two providers share it, for example a billing gateway and webhook verifier.

In that design, ProvideConfig() (Config, error) validates the common settings once. Both ProvideGateway(cfg Config) and ProvideWebhookVerifier(cfg Config) consume the result. Register all three in the App set. Give secrets such as the webhook verification key a typed field and pass them only to consumers that need them.

Use domain-specific configuration types, such as billing.Config, so unrelated integrations do not compete to provide the same generic type.

Multiple Integrations ​

Give each outbound integration its own adapter type. *billing.Gateway and *search.Indexer remain distinct even if each wraps *httpclient.Client. A checkout constructor can receive both types. Register billing.ProvideGateway, search.ProvideIndexer, and checkout.NewService in its App-owned set.

Keep retry policy, headers, and test doubles with the owning adapter. Keep constructor dependencies acyclic. When a service needs a contract, define a narrow interface in the consuming package and bind it in app/wire.

Bind an Interface ​

Wire resolves dependencies by type. When a service requests users.Repository, a provider can expose the selected concrete repository through that interface. This illustrative fragment belongs in an App-owned file under app/wire/.

go
// provideUserRepository exposes the selected repository through the service contract.
func provideUserRepository(source *users.MemoryRepository) users.Repository {
	return source
}

This assumes users.Repository is implemented by *users.MemoryRepository. Add both the implementation constructor and provideUserRepository to appSet. Keep the binding in app/wire. Domain packages declare the interfaces they consume.

Group Related Providers ​

When a service area has several constructors, give it a set in an App-owned file. This illustrative fragment belongs in app/wire/inject_billing_app.go and assumes the three billing constructors exist.

go
package wire

import (
	"github.com/goforj/wire"

	"myapp/internal/billing"
)

// billingSet groups the providers owned by the billing integration.
var billingSet = wire.NewSet(
	billing.ProvideGateway,
	billing.NewRepository,
	billing.NewService,
)

Replace the individual billing entries in appSet with billingSet in app/wire/inject_services_app.go. Preserve the other providers. Register each billing constructor once so Wire can generate wire_gen.go without duplicate providers.

Share a Service Between Apps ​

Each App has an entrypoint and its own Wire graph. To use internal/reports.Service in the default App and admin, add reports.NewService to each App's existing appSet.

AppProvider File
Defaultapp/wire/inject_services_app.go
Adminapp/admin/wire/inject_services_app.go

The same rule applies to the other provider files under app/<name>/wire/. Each App constructs its own service instance. Each App owns its route and command exposure.

Test invalid URLs, malformed and nonpositive timeouts, the default timeout, and any disabled branch directly. Verify live authentication and backend behavior in integration tests. App Lifecycle covers process-wide startup and cleanup.

Common Mistakes ​

Common mistakes

  • Do not add constructors to app/wire/wire_gen.go; it is generated output.
  • Do not register a controller in the service set when it belongs in the HTTP controller set.
  • Do not create dependencies inside commands or controllers when they should be constructor parameters.
  • Do not use package globals to avoid wiring a provider.
  • Do not register two providers for the same raw type when domain-specific adapter types would make the graph clearer.

Next Steps ​