Reputation: 2762
I am facing a situation where my Class constructor takes 2 parameters. One parameter needs to be passed manually by the calling object while the other parameter should be injectd by Structuremap. I want to expose only one constructor that takes parameter value that should be passed manually. I want to hide the second parameter as it should be handled by Structure map itself. Can anyone suggest how it can be done.
I have a scenario like this
public class ProcessPayments
{
public ProcessPayments(String accountNumber, IProcessPayments paymentProcesser)
{
...
}
}
I want to expose the constructor with only first parameter like so
var P = new ProcessPayments("123");
I want Structure Map to automatically inject the IProcessPayments dependency for me based on my configuration.
How can I achieve this?
I can do something like this in my constructor
public ProcessPayments(String accountNumber)
{
_AccountNumber = accountNumber;
_ProcessPayments = ObjectFactory.GetInstance<IProcessPayments >();
}
But this would mean that now I have a dependency on Structure Map itself and I don't like this option. Any other elegant solution?
Upvotes: 1
Views: 841
Reputation: 172875
It seems that accountNumber
is a runtime dependency/value (it can change from call to call). Do not mix runtime values with compile/registration time dependencies. Instead pass the accountNumber
on using a method:
public class ProcessPayments
{
public ProcessPayments(IProcessPayments paymentProcesser) { ... }
public void Process(String accountNumber) { ... }
}
Or, if that's not appropriate, create a factory:
public class ProcessPaymentsFactory : IProcessPaymentsFactory
{
public ProcessPaymentsFactory(IProcessPayments paymentProcesser) { ... }
public ProcessPayments Create(String accountNumber)
{
return new ProcessPayments(accountNumber, this.paymentProcesser);
}
}
Upvotes: 1