如何将我所有的策略模式对象注入列表?

问题描述 投票:0回答:1

我已经实施了策略模式。我有一个基本接口,将选择在运行时将使用该接口的哪种实现。问题是,我不知道一种优雅的方式可以填充一个对象来存储我的所有实现,而无需像这样对它们进行硬编码(将它们更新):

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);
        }
    }
c# dependency-injection strategy-pattern
1个回答
0
投票

在启动期间注册每个实现,并用抽象映射它们,

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容器将注入所有注册的实现。

© www.soinside.com 2019 - 2024. All rights reserved.