我正在嘗試在核心 3.1 上運行的 Service Fabric 應用程式中實作 MediatR。只要我不包含存盤庫(這確實違背了目的),我就可以連接 Queryhandler。
感謝您的關注!
這是我設定 DI 的方法。在 Main() 我有:
var assembly1 = Assembly.GetExecutingAssembly();
var assembly2 = typeof(GetSomeThingQuery).Assembly;
var assembly3 = typeof(IRepository<myDto>).Assembly;
var assembly4 = typeof(myDto).Assembly;
var provider = new ServiceCollection()
.AddLogging()
.AddMediatR(assembly1, assembly2, assembly3, assembly4)
.AddSingleton<IApiExceptionService, ApiExceptionService>()
.BuildServiceProvider();
ServiceRuntime.RegisterServiceAsync("ApiServiceType",
context => new ApiService(context, provider.GetService<IApiExceptionService>(), provider.GetService<IMediator>())).GetAwaiter().GetResult();
我的處理程式看起來像:
namespace Query
{
public class GetSomeThingQuery: IRequest<List<myDto>>
{
public string para1{ get; set; }
public string para2 { get; set; }
}
public class GetSomeThingQueryHandler : IRequestHandler<GetSomeThingQuery, List<myDto>>
{
private readonly IRepository<myDto> _repository;
public GetSomeThingQueryHandler (IRepository<myDto> repository)
{
_repository = repository;
}
public async Task<List<myDto>> Handle(GetSomeThingQueryHandler Query request, CancellationToken cancellationToken)
{
var test = await _repository.CallTheDatabaseAndGetTheResult(request.para1);
return null; //this is just here as a place holder.
}
}
}
我得到的錯誤是:
System.InvalidOperationException: Error constructing handler for request of type MediatR.IRequestHandler`2[Query.GetSomeThingQuery,System.Collections.Generic.List`1[Sql.myDto]]. Register your handlers with the container. See the samples in GitHub for examples.
---> System.InvalidOperationException: Unable to resolve service for type 'IRepository`1[myDto]' while attempting to activate 'Query.GetSomeThingQuery'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
我嘗試了各種設定容器的方法,但沒有任何效果。如果我洗掉以下行,MediatR 可以決議處理程式。當我包含 repo 時,它無法決議處理程式。
private readonly IRepository<myDto> _repository;
public GetSomeThingQueryHandler (IRepository<myDto> repository)
{
_repository = repository;
}
uj5u.com熱心網友回復:
您需要添加將在 DI 容器中使用的所有類。您尚未注冊存盤庫。
您需要添加:
.AddScoped(typeof(IRepository<>), typeof(Repository<>));
到你的ServiceCollection.
如果您不想一一注冊您的課程,我建議Scrutor幫助注冊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528913.html
