Home > database >  Inject array of same interface type to class constructor
Inject array of same interface type to class constructor

Time:10-30

I have the following class that get IPersonOrderingStrategy[]:

public class PersonCollection : IPersonCollection
    {
        private IDictionary<int, IPerson> _persons;
        private IPerson _maxOrMinPerson;
        private readonly IPersonOrderingStrategy[] _personOrderingStrategies;

        private string _propertyName { get; set; }
        private string _maxMinOrdering { get; set; }

        public PersonCollection(IPersonOrderingStrategy[] personOrderingStrategies)
        {
            _persons = new Dictionary<int, IPerson>();
            _personOrderingStrategies = personOrderingStrategies;
        }

and I register all class:

public void ConfigureServices()
        {
            _serviceColletcion.AddTransient<IPerson, Person>();
            _serviceColletcion.AddTransient<IPersonCollection, PersonCollection>();
            _serviceColletcion.AddTransient<IPersonOrderingStrategy, MaximumPersonsOrdering>();
            _serviceColletcion.AddTransient<IPersonOrderingStrategy, MaximumPersonsOrdering>();
            _serviceColletcion.AddTransient<IPersonFactory, PersonFactory>();
            _serviceProvider = _serviceColletcion.BuildServiceProvider();
        }

while I'm coming to resolve the IPersonCollection:

        {
            var personCollection = _applicationServices.Resolve<IPersonCollection>();
}

I'm getting the following error: Unable to resolve service for type 'Model.Person.IPersonOrderingStrategy[]' while attempting to activate 'BusinessComponent.Person.PersonCollection

my resolver looks like this:

public T Resolve<T>()
        {
            return (T)_serviceProvider.GetService(typeof(T));
        }

what am I doing wrong?

CodePudding user response:

I assume your are using Microsoft.Extensions.DepencyInjection.

The support for injection of all implementations of T uses IEnumerable<T> instead of T[]. This is a design choice of the DI library.

Change your constructor to

public PersonCollection(IEnumerable<IPersonOrderingStrategy> personOrderingStrategies)
{
    _persons = new Dictionary<int, IPerson>();
    _personOrderingStrategies = personOrderingStrategies.ToArray();
}

See https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-registration-methods

  • Related