Procyon|Docs
ComponentsConditions

Attaching Conditions

Apply one or more conditions to a registered component.

component.Register returns a registration handle. Use Conditional on that handle to attach runtime conditions.

register.go
func init() {
	component.Register(NewAuditService).
		Conditional(ProfileCondition{Profile: "production"})
}

When a component has multiple conditions, every condition must match.

register.go
func init() {
	component.Register(NewMetricsReporter).
		Conditional(ProfileCondition{Profile: "production"}).
		Conditional(HasMetricsExporter{})
}

In this example, NewMetricsReporter is loaded only in the production profile and only when a MetricsExporter can be resolved.

Conditional implementations

Conditions are useful when several implementations share the same interface.

mail.go
type Mailer interface {
	// Send delivers a message through the implementation selected for this profile.
	Send(to string, body string) error
}

func init() {
	component.Register(NewSmtpMailer, component.WithName("mailer")).
		Conditional(ProfileCondition{Profile: "production"})

	component.Register(NewConsoleMailer, component.WithName("mailer")).
		Conditional(ProfileCondition{Profile: "development"})
}

Only one mailer component should match for a given runtime state. If multiple matching components share the same name, registration or loading will fail instead of silently choosing one.

Guidance

  • Attach conditions at registration time.
  • Keep each condition focused on one inclusion rule.
  • Chain conditions when a component needs multiple rules.
  • Prefer separate condition types over one large condition with many branches.