我面临一个问题,即未调用Mediatr命令处理程序。 我具有以下解决方案结构。
Project.sln
-> Application layer (.NET standard class library)
-> Jobs (.NET standard class library)
-> Job Server (.NET Core console app)
该想法是Job Server使用调度程序(Quartz.NET)执行Jobs。实际的业务逻辑在应用程序层中。应用程序层使用CQRS模式,该模式使用Mediatr连接。我正在使用Microsoft依赖项注入库。
作业服务器Main
方法(带有DI代码):
public class Program
{
static ManualResetEvent _quitEvent = new ManualResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("Job Server started");
//DI setup
var serviceProvider = new ServiceCollection()
.AddQuartz()
.AddTransient<InitializeJobServer>()
.AddTransient<ProcessAdRssFeedsJob>()
.AddScoped<IConfigService, ConfigService>()
.AddScoped<IRssService, RssService>()
.AddScoped<IBaseService, BaseService>()
.AddMediatR(typeof(ProcessAdSectionsRssCommand).GetType().Assembly)
.AddDbContext<MyDbContext>(options =>
options.UseNpgsql("xxx"))
.AddMemoryCache()
.BuildServiceProvider();
Console.CancelKeyPress += (sender, eArgs) => {
_quitEvent.Set();
eArgs.Cancel = true;
};
Task.Run(async () =>
{
await serviceProvider.GetService<InitializeJobServer>().Start();
});
_quitEvent.WaitOne();
Console.WriteLine("Job Server ended");
}
}
Quartz.net作业中的代码:
[DisallowConcurrentExecution]
public class ProcessAdRssFeedsJob : IJob
{
private readonly IMediator _mediator;
public ProcessAdRssFeedsJob(IMediator mediator)
{
_mediator = mediator;
}
public Task Execute(IJobExecutionContext context)
{
try
{
_mediator.Send(new ProcessAdSectionsRssCommand());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return null;
}
}
Mediatr命令:
public class ProcessAdSectionsRssCommand : IRequest<bool>
{
public class Handler : IRequestHandler<ProcessAdSectionsRssCommand, bool>
{
private readonly MyDbContext _context;
private readonly IRssService _rssService;
private readonly IConfigService _configService;
public Handler(
MyDbContext context,
IRssService rssService,
IConfigService configService)
{
_context = context;
_rssService = rssService;
_configService = configService;
}
public async Task<bool> Handle(ProcessAdSectionsRssCommand request, CancellationToken cancellationToken)
{
var config = await _configService.GetAllConfigs();
var r0 = await _rssService.GetAdSectionRssUrls();
// etc.
return true;
}
}
}
调试后,我得出结论,代码初始化ProcessAdSectionsRssCommand
类后停止执行(如果我创建一个空的构造函数,它将被执行)。不幸的是,我没有任何实际的错误消息,我认为可能会吞下某种异常。据我所知,Handler
类永远不会初始化。
我怀疑这是与DI + Mediatr相关的问题。有人有什么想法吗? 谢谢。