如何把这种服务定位器模式转变为真正的依赖注入模式? [英] How to turn this Service Locator pattern into true Dependency Injection pattern?
问题描述
我问一个更普遍的问题在一分钟前:<一href="http://stackoverflow.com/questions/9372294/how-to-organize-di-framework-usage-in-an-application">How组织DI框架使用情况的应用程序和我得到的反馈是,我使用的是Service Locator模式,而不是真正的DI如指出Martin Fowler的位置: http://martinfowler.com/articles/injection.html
I asked a more general question a minute ago: How to organize DI Framework usage in an application?, and the feedback I got was that I was using a Service Locator Pattern rather than true DI as is pointed out by Martin Fowler here: http://martinfowler.com/articles/injection.html
其实,我看了那篇文章只是一天,但显然还没有完全掌握它。
Actually, I read that article just the other day, but apparently haven't quite grasped it.
所以我们可以说我有以下的code:
So let's say I have the following code:
interface ICardReader
{
string GetInfo();
void SetDebugMode(bool value);
void Initialize(string accountToken);
void ShowAmount(string amount);
void Close();
ICreditCardInfo GetCardInfo();
}
public class MagTekIPAD: ICardReader
{
public ICreditCardInfo GetCardInfo()
{
var card = GetCardDataFromDevice();
// apparently the following line is wrong?
var ccInfo = Inject<ICreditCardInfo>.New();
ccInfo.Track1 = MakeHex(card.EncTrack1);
ccInfo.Track2 = MakeHex(card.EncTrack2);
ccInfo.MagSignature = MakeHex(card.EncMP);
ccInfo.MagSwipeKeySN = MakeHex(card.KSN);
ccInfo.MagSignatureStatus = MakeHex(card.MPSts);
ccInfo.MagDeviceSN = ipad.Serial;
ccInfo.MSREncryptType = "MAGENSA_V5";
return ccInfo;
}
// Other implementation details here ...
}
在这个例子中,我可以注入的依赖到构造 - 我认为这是解决'这个'情况下的正确方法。
In this example I could inject the dependency into the constructor—and I think that's the correct way to fix 'this' scenario.
但是,如果我真的需要创建一个未知的数字有问题的对象(或者还有没有其他合理的原因我想有一个需要创建的类中的飞的依赖)?
But what if I actually need to create an unknown number of the object in question (or are there any other legitimate reason I'd have a need to create the dependency on the fly in the class)?
推荐答案
这个例子给我说,你尝试namingly创建一个数据传输对象的IM pression ICreditCardInfo
使用IoC容器。这些对象不应该有这样一个服务,任何真正的依赖关系。正确的方法来创建DTO的是使用新
操作符:
This example gives me the impression that you try to create a data transfer object namingly ICreditCardInfo
using an IoC container. Such objects should not have any real dependencies like a service. The proper way to create DTOs is to use the new
operator:
return new CreditCardInfo(
MakeHex(card.EncTrack1),
MakeHex(card.EncTrack2),
MakeHex(card.EncMP),
MakeHex(card.KSN),
MakeHex(card.MPSts),
ipad.Serial,
"MAGENSA_V5");
这篇关于如何把这种服务定位器模式转变为真正的依赖注入模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!