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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With