c# - 如何解析不同类型服务的 IEnumerable

标签 c# asp.net .net dependency-injection ienumerable

这是我的界面:

public interface ISocialService<T> where T : ISocialModel
{
    public Task<List<T>> GetPosts();
}

我有这个接口(interface)的 2 个实现。 这就是我尝试注册它们的方式

services.AddScoped<ISocialService<RedditPost>, RedditService>();
services.AddScoped<ISocialService<HackerNewsModel>, HackerNewsService>();

最后这就是我尝试解决它们的方式。

public ScrapeJob(IEnumerable<ISocialService<ISocialModel>> socialServices)
{
    _socialServices = socialServices;
}

但是 socialServices 是空的。 我认为问题出在 ISocialModel 上。 有人对我如何正确注册或解决它们有任何建议吗?

我想使用通用接口(interface)的原因是我想像这样将特定服务注入(inject) Controller :

public HackerNewsController(ISocialService<HackerNewsModel> socialService)
        {
            _socialService = socialService;
        }

最佳答案

问题是你注入(inject)了通用接口(interface)IEnumerable<ISocialService<ISocialModel>>但是你没有任何实现 ISocialService<ISocialModel> 的类相反,你有 ISocialService<T>在类中实现。
所以我们需要按照下面的方式更新代码

public interface ISocialModel
{

}

public class RedditModel : ISocialModel
{

}

public interface ISocialService
{
     Task<List<ISocialModel>> GetPosts();
}

public interface ISocialService<T>: ISocialService where T : ISocialModel
{
     Task<List<T>> GetPosts();
}

public abstract class SocialServiceBase<T> : ISocialService<T> where T : ISocialModel

{
    async Task<List<ISocialModel>> ISocialService.GetPosts()
    {
        var posts = await GetPosts();

        return posts.Cast<ISocialModel>().ToList();
    }

   public abstract Task<List<T>> GetPosts();
    
}

public class RedditSocialService : SocialServiceBase<RedditModel>
{
    public override Task<List<RedditModel>> GetPosts()
    {
        //TODO: past your implementation here


    }
}

所以现在在注册中你可以写下面的代码

    services.AddScoped<ISocialService, RedditService>(); 
    services.AddScoped<ISocialService, HackerNewsService>();

以后在类里面你可以这样使用

  class ScrapeJob
{
    private IEnumerable<ISocialService> _socialServices;

    public ScrapeJob(IEnumerable<ISocialService> socialServices)
    {
        _socialServices = socialServices;
    }


    public async Task DoScrapeJob()
    {
        foreach( var service in _socialServices)
        {
           var posts = await service.GetPosts();
        }
    }
}

关于c# - 如何解析不同类型服务的 IEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66447410/

相关文章:

.net - 查询托管环境中接口(interface)的 IronPython 脚本

c# - f 和 f 有什么区别

.net - 如何将 ContextMenuStrip 附加到 NotifyIcon

c# - 停止其他脚本中的协程

c# - 接受字母数字字符(6-10 个字符)的正则表达式 .NET、C#

C# 创建其他应用程序可以看到的系统事件

c# - 如何使用 C# 实现 Modbus 功能 20?

c# - 以其语言获取文化显示名称

c# - gridview rowdatabound 事件中的 e.Row.DataItem 错误

Asp.net mvc用户管理