这是我的界面:
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/