In StructureMap, there are more idiomatic and declarative ways to handle this dependency registration and resolution. Here are a few approaches:
- Using Registry Configuration:
public class PaymentFraudDetectorRegistry : Registry
{
public PaymentFraudDetectorRegistry(NoFraudSettings settings)
{
switch (settings.Mode)
{
case FraudDetectionMode.Active:
For<IPaymentFraudDetector>().Use<NoFraudPaymentFraudDetector>();
break;
case FraudDetectionMode.Passive:
For<IPaymentFraudDetector>().Use<PassivePaymentFraudDetectorDecorator>();
break;
default:
For<IPaymentFraudDetector>().Use(NullPaymentFraudDetector.Instance);
break;
}
}
}
- Using Conditional Registration:
public class PaymentFraudDetectorRegistry : Registry
{
public PaymentFraudDetectorRegistry()
{
For<IPaymentFraudDetector>()
.When(context =>
context.GetInstance<NoFraudSettings>().Mode == FraudDetectionMode.Active)
.Use<NoFraudPaymentFraudDetector>()
.When(context =>
context.GetInstance<NoFraudSettings>().Mode == FraudDetectionMode.Passive)
.Use(ctx =>
new PassivePaymentFraudDetectorDecorator(
ctx.GetInstance<NoFraudPaymentFraudDetector>()
))
.Otherwise()
.Use(NullPaymentFraudDetector.Instance);
}
}
- Using Lambda Registration:
public class PaymentFraudDetectorRegistry : Registry
{
public PaymentFraudDetectorRegistry(NoFraudSettings settings)
{
For<IPaymentFraudDetector>().Use(context =>
settings.Mode switch
{
FraudDetectionMode.Active => context.GetInstance<NoFraudPaymentFraudDetector>(),
FraudDetectionMode.Passive => new PassivePaymentFraudDetectorDecorator(
context.GetInstance<NoFraudPaymentFraudDetector>()
),
_ => NullPaymentFraudDetector.Instance
}
);
}
}
Each approach has its pros:
- The first method is straightforward and explicit
- The second method offers more flexible conditional registration
- The third method keeps the logic similar to your original switch expression
The key improvements are:
- Moving the logic into the container configuration
- Making the dependency resolution more declarative
- Removing the need for a manual factory method
When setting up your container, you would then add this registry:
var container = new Container(c =>
{
c.AddRegistry(new PaymentFraudDetectorRegistry(settings));
});
This approach leverages StructureMap's built-in configuration capabilities and makes the dependency resolution more explicit and maintainable.