我正在尝试找出最简单的方法来测试针对我的框架的服务注册方法。我正在创建动态服务,注册情况如下:
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);
除了我的注册休息服务方法外,我还有很多其他服务正在注册,例如:
services.AddTransient(restServiceType, (IServiceProvider serviceProvider) =>
{
var restService = (IRestEzService<TEntity, TDTO>)
ActivatorUtilities.CreateInstance(serviceProvider, restServiceImplementationType);
serviceOption.EventMapping?.Register(serviceProvider, restService);
return restService;
});
如何确保我的出厂配置已正确注册,如何创建服务集合进行测试?
答案 0 :(得分:11)
创建一个ServiceCollection
var services = new ServiceCollection();
调用您的注册功能,然后断言您的restServiceType
已添加。
接下来从服务集合中构建提供者,解决restServiceType
var provider = services.BuildServiceProvider();
var restService = provider.GetService(restServiceType);
并断言它是根据需要创建的。
现在,这完全基于您的示例中当前显示的内容,因为我不知道其他任何依赖项。