在MVC Core DI中注册服务集合 [英] 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));
}
}
我如何在MVC核心DI容器中注册它?我发明了这样的东西:
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?
推荐答案
向 ServiceCollection
注册多个实现.
DI容器将识别 IEnumerable< IQualifier>
依赖项,并将通过所有已注册的实现.
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.
这篇关于在MVC Core DI中注册服务集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!