我正在尝试找出最简单的方法来测试我的框架的服务注册方法。我正在创建动态服务,我的注册看起来像这样:
var messageHubConfig = new DynamicHubServiceConfiguration<Message, MessageDTO>();
messageHubConfig.SetDynamicHubOptions<AstootContext>(async (context, dto) =>
{
return await context.ConversationSubscriptions
.Where(x => x.ConversationId == dto.ConversationId
&& x.IsSubscribed)
.Distinct()
.Select(x => x.User.UniqueIdentifier)
.ToListAsync();
});
messageHubConfig.RequiresDynamicValidator = false;
messageHubConfig.EventMapping.AddCreateEvent(async (sp, obj, dto) =>
{
var conversationService = sp.GetService<IRestEzService<Conversation, ConversationDTO>>();
var conversationDTO = await conversationService.Get(new object[] { dto.ConversationId });
var hubTaskQueue = sp.GetService<IHubServiceTaskQueue>();
hubTaskQueue.QueueDynamicCreate(conversationDTO);
}).When(async (sp, dto) => {
var context = sp.GetService<AstootContext>();
return await context.Conversations.Where(x => x.Id == dto.ConversationId).Where(x => x.Messages.Count == 1).AnyAsync();
});
//Registers service with a hub
restConfiguration.RegisterRestService(typeof(IMessageDTOService),
typeof(MessageDTOService),
messageHubConfig);
在我的 Register Rest Service 方法中,我有很多不同的服务正在注册,例如:
services.AddTransient(restServiceType, (IServiceProvider serviceProvider) =>
{
var restService = (IRestEzService<TEntity, TDTO>)
ActivatorUtilities.CreateInstance(serviceProvider, restServiceImplementationType);
serviceOption.EventMapping?.Register(serviceProvider, restService);
return restService;
});
如何确保我的出厂配置已正确注册,如何创建用于测试的服务集合?
最佳答案
创建一个ServiceCollection
,
var services = new ServiceCollection();
调用您的注册函数,然后断言您的 restServiceType
已添加。
接下来从服务集合构建一个提供者,解析restServiceType
var provider = services.BuildServiceProvider();
var restService = provider.GetRequiredService(restServiceType);
并断言它是根据需要创建的。
如果服务无法解析目标类型,GetRequiredService
扩展方法将抛出异常。
现在这完全基于您示例中当前显示的内容,因为我不知道任何其他依赖项。
关于c# - 单元测试 IServiceCollection 注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51180523/