简体   繁体   中英

How Can I Inject All my Strategy Pattern Objects Into a List?

I've implemented the strategy pattern. I have a base interface, and will be selecting which implementation of this interface I will be using at runtime. The problem is, I don't know of an elegant way that I can populate an object to store all my implementations without hardcoding them (new-ing them up) as such:

public class FixMessageFormatter
{
    List<IMessageFormat> _messageFormats = new List<IMessageFormat>{ new MassQuoteMessageFormat(), }
    // ... Other code.
}

This is not elegant. If I have over 50 implementations of the IMessageFormat , this can get ugly quickly. I've heard of dependency injection, but was unsure of how I'd apply it to this simple example.

For context, the following is my interface, and a single implementation.

Interface

    public interface IMessageFormat
    {
        List<FixMessageType> MessageType { get; }
        bool IsProperType(FixMessageType fixMessageType);
        StringBuilder FormatMessage(FixMessage fixMessage);
    }

Implementation

    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);
        }
    }

Register each implementation during startup, mapping them with the abstraction,

ConfigureServices(IServiceCollection services)

services.AddScoped<IMessageFormat, MassQuoteMessageFormat>(); //<-- or other lifetime scope
//add other implementation...
//they could be done via reflection to auto register.

services.AddScoped<FixMessageFormatter>(); //also adding target

and inject an IEnumerable<IMessageFormat> into the target dependent instance.

public class FixMessageFormatter {
    private List<IMessageFormat> _messageFormats;

    public FixMessageFormatter (IEnumerable<IMessageFormat> formats) {
        _messageFormats = formats.ToList();
    }

    // ... Other code.
}

The DI container will inject all registered implementations.

Reference Logging in .NET Core and ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM