我刚刚开始学习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
}
}
支付处理器
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
}
}
简单的东西。现在我有了一个类,它接受接口作为构造函数中的参数….
信用卡处理器
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
(这似乎是默认的)? 最佳答案
我自己没用过Tinyioc,但我想你想:
TinyIoCContainer.Current.Register(typeof(IPaymentProcessor),
typeof(AmexPaymentProcessor));
(如果您想使用美国运通。)
还有许多其他可用的
Register
重载,包括一个需要使用名称的重载,这在解析时可能很有用。这真的取决于你想达到什么目标,但这个问题并不是很清楚。