我已经实施了策略模式。我有一个基本接口,将选择在运行时将使用该接口的哪种实现。问题是,我不知道一种优雅的方式可以填充一个对象来存储我的所有实现,而无需像这样对它们进行硬编码(将它们更新):
public class FixMessageFormatter
{
List<IMessageFormat> _messageFormats = new List<IMessageFormat>{ new MassQuoteMessageFormat(), }
// ... Other code.
}
这不优雅。如果我有IMessageFormat
的50多个实现,这很快就会变得很难看。我听说过依赖注入,但是不确定如何将其应用于此简单示例。
对于上下文,以下是我的界面和单个实现。
接口
public interface IMessageFormat
{
List<FixMessageType> MessageType { get; }
bool IsProperType(FixMessageType fixMessageType);
StringBuilder FormatMessage(FixMessage fixMessage);
}
实施
public class MassQuoteMessageFormat : IMessageFormat
{
public List<FixMessageType> MessageType => new List<FixMessageType>{ FixMessageType.MassQuote };
public StringBuilder FormatMessage(FixMessage fixMessage)
{
var stringBuilder = new StringBuilder();
// ... Code
return stringBuilder;
}
public bool IsProperType(FixMessageType fixMessageType)
{
return MessageType.Contains(fixMessageType);
}
}
在启动期间注册每个实现,并用抽象映射它们,
services.AddScoped<IMessageFormat, MassQuoteMessageFormat>(); //<-- or other lifetime scope
//add other implementation...
//they could be done via reflection to auto register.
并将IEnumerable<IMessageFormat>
注入目标依赖项。
public class FixMessageFormatter {
private List<IMessageFormat> _messageFormats;
public FixMessageFormatter (IEnumerable<IMessageFormat> formats) {
_messageFormats = formats.ToList();
}
// ... Other code.
}
DI容器将注入所有注册的实现。