Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register collection of services in MVC Core DI

I`ve got simple class with strategies.

 public class LinkQualifier : ILinkQualifier
    {
        private readonly IEnumerable<IQualifier> _qualifiers;

        public LinkQualifier(IEnumerable<IQualifier> qualifiers)
        {
            _qualifiers = qualifiers;
        }

        public IQualifier Qualify(Uri uri)
        {
            return _qualifiers.FirstOrDefault(q => q.CanQualify(uri));
        }


    }

How i can register it in MVC core DI container? I invented something like this:

services.AddTransient<ILinkQualifier, LinkQualifier>((ctx =>
            {
                var qualifiers = new List<IQualifier> {...};
                return new LinkQualifier(qialifiers);
            }));

But thats looks badly... is there a better solution?

like image 668
Surgerer Avatar asked Nov 22 '18 09:11

Surgerer


People also ask

How does DI work in .NET Core?

ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.

What is IServiceCollection in .NET Core?

AddScoped(IServiceCollection, Type, Type) Adds a scoped service of the type specified in serviceType with an implementation of the type specified in implementationType to the specified IServiceCollection.

How can we inject the service dependency into the controller?

ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.


1 Answers

Register the multiple implementations with the ServiceCollection.

The IEnumerable<IQualifier> dependency will be recognized by the DI container and will pass all registered implementations.

services.AddTransient<IQualifier, QualifierOne>();
services.AddTransient<IQualifier, QualifierTwo>();
services.AddTransient<IQualifier, QualifierThree>();

services.AddTransient<ILinkQualifier, LinkQualifier>();

It’s worth making it clear that the implementations will be added in the order they are registered. They will be returned in that same order when injected into calling code. Depending on your requirements, this may be useful and important.

Reference ASP.NET Core Dependency Injection – Registering Multiple Implementations of an Interface

like image 145
Fabio Avatar answered Oct 06 '22 01:10

Fabio