I am just beginning to learn about IoC and Dependency Injection. I am planning on doing a MonoTouch project and wanted to use TinyIoC but I wanted to test it out first. I'm creating a dummy credit card processing console app and I'm having trouble with how to configure TinyIoC since I have multiple implementations of my interface. This is my test app.
Interface:
public interface IPaymentProcessor
{
void ProcessPayment(string cardNumber);
}
Two Implementations of the interface:
VisaPaymentProcessor
public class VisaPaymentProcessor : IPaymentProcessor
{
public void ProcessPayment(string cardNumber)
{
if (cardNumber.Length != 13 && cardNumber.Length != 16)
{
new ArgumentException("Card Number isn't the correct length");
}
// some code for processing payment
}
}
AmexPaymentProcessor
public class AmexPaymentProcessor : IPaymentProcessor
{
public void ProcessPayment(string cardNumber)
{
if (cardNumber.Length != 15)
{
new ArgumentException("Card Number isn't the correct length");
}
// some code for processing the payment
}
}
Simple stuff. Now I have a class that accepts the interface as a parameter in the constructor....
CreditCardProcessor
public class CreditCardProcessor
{
public IPaymentProcessor PaymentProcessor { get; set; }
public CreditCardProcessor(IPaymentProcessor processor)
{
this.PaymentProcessor = processor;
}
public void ProcessPayment(string creditCardNumber)
{
this.PaymentProcessor.ProcessPayment(creditCardNumber);
}
}
My console app looks like this....
class Program
{
static void Main(string[] args)
{
TinyIoCContainer.Current.AutoRegister();
var creditCardProcessor = TinyIoCContainer.Current.Resolve<CreditCardProcessor>();
creditCardProcessor.ProcessPayment("1234567890123456"); // 16 digits
}
}
So I am trying to figure out how to tell the Resolve
which implementation of the interface to pass to the constructor. If I run this code, I will always use the VisaPaymentProcessor
implementation.
So how can I make TinyIoC pass the AmexPaymentProcessor
implementation to the constructor rather than the VisaPaymentProcessor
(which seems to be the default)?