我收到以下异常:
System.InvalidOperationException:'无法从根提供程序解析作用域服务'OSPC.Shared.Core.Data.IRepository`1 [OSPC.Configuration.Objects.SignalMetaData]'。 在CommandDispatcher类的ActivatorUtilities.CreateInstance行上。
在调查在CommandDispatcher类中注入的参数serviceProvider时,我可以在ResolvedServices集合中看到122个项目(所有与Microsoft相关的服务),但是在ConfigureServices方法中注册的我的服务都不在该集合中。
为什么我自己的注册服务没有出现?
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILogManager, LogManager>();
services.AddScoped<IDbContext>(c => new OSPCContext(Configuration.GetConnectionString("OSPCConnectionstring")));
services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));
services.AddSingleton<ICommandDispatcher, CommandDispatcher>();
}
}
public class CommandDispatcher : ICommandDispatcher
{
private readonly IServiceProvider _serviceProvider;
private readonly Dictionary<string, Type> _registeredCommands = new Dictionary<string, Type>();
public CommandDispatcher(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_registeredCommands.Add("CreateSignalMetaData", typeof(CreateSignalMetaDataHandler));
_registeredCommands.Add("CreatePDCQueryConfig", typeof(CreatePDCQueryConfigHandler));
}
public object Dispatch(string json)
{
JObject jObject = JObject.Parse(json);
JToken jToken = jObject["type"];
if (jToken == null)
{
throw new Exception("The parameter type is missing in the JSON string (Pay attention: it is casse sensitive).");
}
Type typeCommandHandler = _registeredCommands[jToken.ToString()];
dynamic commandHandler = ActivatorUtilities.CreateInstance(_serviceProvider, typeCommandHandler);
dynamic o = jObject.ToObject(commandHandler.InputType);
return commandHandler.Handle(o);
}
}
[Route("api/[controller]")]
[ApiController]
public class ConfigurationController : ControllerBase
{
private readonly ILog _logger;
private readonly IConfigurationService _configurationService;
private readonly ICommandDispatcher _commandDispatcher;
public ConfigurationController(ICommandDispatcher commandDispatcher)
{
this._commandDispatcher = commandDispatcher;
}
// POST api/configuration
[HttpPost]
public IActionResult Post([FromBody] dynamic json)
{
var result = _commandDispatcher.Dispatch(json.ToString());
return Ok(result);
}
}
using OSPC.Configuration.Msg;
using OSPC.Configuration.Objects;
using OSPC.Shared.Core.Commands;
using OSPC.Shared.Core.Data;
using System.Collections.Generic;
namespace OSPC.Configuration.CommandHandler
{
public class CreateSignalMetaDataHandler : CommandHandlerBase<CreateSignalMetaDataRequest, CreateSignalMetaDataResponse>
{
private readonly IRepository<SignalMetaData> _signalMetaDataRepository;
public CreateSignalMetaDataHandler(IRepository<SignalMetaData> signalMetaDataRepository)
{
_signalMetaDataRepository = signalMetaDataRepository;
}
public override CreateSignalMetaDataResponse Handle()
{
Output.Success = false;
var result = new CreateSignalMetaDataResponse
{
SignalMetaDatas = new List<CreateSignalMetaDataResponse.SignalMetaData>()
};
foreach (var item in Input.Payload.SignalMetaDatas)
{
var signalMetaData = new Objects.SignalMetaData()
{
SignalName = item.SignalName,
Unit = item.Unit,
SignalDescription = item.SignalDescription,
Source = item.Source
};
_signalMetaDataRepository.Insert(signalMetaData);
result.SignalMetaDatas.Add(new CreateSignalMetaDataResponse.SignalMetaData()
{
Id = signalMetaData.Id,
SignalName = signalMetaData.SignalName,
Unit = signalMetaData.Unit,
SignalDescription = signalMetaData.SignalDescription,
Source = signalMetaData.Source
});
}
Output.Success = true;
return result;
}
}
}
答案 0 :(得分:1)
对于IRepository<>
,它是作用域,对于ICommandDispatcher
,它是单例。对于ActivatorUtilities.CreateInstance(_serviceProvider, typeCommandHandler);
,_serviceProvider
是无法解决作用域服务的根提供者。
请尝试下面的代码来创建新的作用域提供程序。
dynamic commandHandler = ActivatorUtilities.CreateInstance(
_serviceProvider.CreateScope().ServiceProvider, typeCommandHandler);
答案 1 :(得分:0)
Tao Zhou的解决方案正在工作,但我不知道该解决方案是否还解决了圈养依赖性问题?
我已通过以下方式解决了该问题: 在启动类中,我将其更改为AddScoped代替AddSingleton
services.AddScoped<ICommandDispatcher, CommandDispatcher>();
否则,我会遇到专属依赖性问题(https://andrewlock.net/the-dangers-and-gotchas-of-using-scoped-services-when-configuring-options-in-asp-net-core/)。
我们不能将其定义为Singleton(CommandDispatcher),因为否则,我们会遇到圈养依赖性问题,因为CommandDispatcher最终将实例化CommandHandler(fe CreateSignalMetaDataHandler),并且在构造函数中必须注入一个或多个EFRepository,而这又必须注入注入了DbContext。 目的是必须限制DbContext的实例化。因此,每个HTTP请求必须注入一个DbContext实例,并且只有一个实例被注入。因此,如果我们使用不同的存储库,那么它们都必须共享相同的DbContext。每个HTTP请求都有其自己的DbContext,并且不同的HTTP请求将具有不同的DbContext。 因为必须限制DbContext的范围,所以也必须一直限制CommandDispatcher的范围,以避免俘虏依赖性问题。因此CommandDispatcher不能定义为Singleton。