我在我的项目 MediatR 中使用。这就是我在我的服务类中所拥有的:
public class WebShopServices : IWebShopServices
{
private readonly IMediator _mediator;
public WebShopServices(IMediator mediator)
{
_mediator = mediator;
}
public void UpdateCustomerAddress(UpdateAddressInformationCommand updateAddressInformation)
{
_mediator.Send(updateAddressInformation);
}
}
这是我的处理程序
public class UpdateCustomerAddressHandler : RequestHandler<UpdateAddressInformationCommand>
{
private readonly OnlineSalesService _client;
private readonly IDataContractsFactory _factory;
private readonly IParameterValidator _validator;
public UpdateCustomerAddressHandler(OnlineSalesService client,
IDataContractsFactory factory, IParameterValidator validator)
{
_client = client;
_factory = factory;
_validator = validator;
}
protected override void HandleCore(
UpdateAddressInformationCommand updateAddressInformation)
{
_validator.Validate(updateAddressInformation);
var updateAddressCommand =
_factory.CreateCustomerDefaultAddressCommand(updateAddressInformation);
try
{
_client.SetCustomerDefaultAddress(updateAddressCommand);
}
catch (Exception ex)
{
throw new CustomerException("Something happened with the service.", ex);
}
}
}
这是我的模型课:
public class UpdateAddressInformationCommand : IRequest
{
public string CustomerNumber { get; set; }
public AddressInformation AddressInformation { get; set; }
}
这就是我在依赖注入配置中写的:
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
builder.RegisterInstance(Console.Out).As<TextWriter>();
builder.Register<SingleInstanceFactory>(ctx => {
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
builder.Register<MultiInstanceFactory>(ctx => {
var c = ctx.Resolve<IComponentContext>();
return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
});
builder.RegisterType<GetCustomerDetailsResultHandler>()
.As<IRequestHandler<GetCustomerDetailsQuery,GetCustomerDetailsResult>>();
builder.RegisterType<UpdateCustomerAddressHandler>()
.As<RequestHandler<UpdateAddressInformationCommand>>();
它一直给我这个例外:
{"请求的服务'MediatR.IRequestHandler`2[[Service.DataContracts.UpdateAddressInformationCommand, Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[MediatR.Unit, MediatR, Version=2.0.0.0, Culture =neutral, PublicKeyToken=null]]' 尚未注册。为避免此异常,请注册提供服务的组件,使用 IsRegistered() 检查服务注册,或使用 ResolveOptional() 方法解决可选依赖项。 "}
有谁知道如何解决这个问题?