我刚开始学习IoC和依赖注入。我计划做一个MonoTouch项目,并想使用TinyIoC,但我想先测试一下。我正在创建一个虚拟信用卡处理控制台应用程序,但我在如何配置TinyIoC方面遇到了麻烦,因为我有多个接口实现。这是我的测试应用程序。
接口:
public interface IPaymentProcessor
{
void ProcessPayment(string cardNumber);
}
接口的两个实现:
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
}
}
很简单的东西。现在我有一个类,它在构造函数中接受接口作为参数....
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);
}
}
我的控制台应用程序长这样...
class Program
{
static void Main(string[] args)
{
TinyIoCContainer.Current.AutoRegister();
var creditCardProcessor = TinyIoCContainer.Current.Resolve<CreditCardProcessor>();
creditCardProcessor.ProcessPayment("1234567890123456"); // 16 digits
}
}
所以我正在尝试弄清楚如何告诉Resolve
将接口的哪个实现传递给构造函数。如果我运行这段代码,我将始终使用VisaPaymentProcessor
实现。
那么我该如何让TinyIoC传递AmexPaymentProcessor
实现到构造函数中,而不是VisaPaymentProcessor
(似乎是默认值)?
VisaPaymentProcessor
是TinyIoC使用的“默认”实现。我该如何让TinyIoC将AmexPaymentProcessor
实现传递给构造函数呢?抱歉没有表述清楚。 - Ryan Alfordpublic CreditCardProcessor(IPaymentProcessor processor)
。 - tom redfern