我正在使用新的 ASP.NET Core,目前正在创建一个我想从 JavaScript 前端调用的 API。
我想使用中介者模式来降低耦合度,找到了库MediatR来自 Jimmy Bogard。
我的问题在于使用 DI 中的构建将其连接起来,我尝试查看 examples ,但看不到破解它是如何绑定(bind)到启动类中的 ConfigureServices 方法的。
有没有人有任何见解?
更新:我通过我的 ConfigureService 方法让它工作了:
services.AddScoped<SingleInstanceFactory>(p => t => p.GetRequiredService(t));
services.Scan(scan => scan
.FromAssembliesOf(typeof(IMediator), typeof(MyHandler.Handler))
.AddClasses()
.AsImplementedInterfaces());
最佳答案
截至2016年7月,MediatR的作者Jimmy Bogard发布了一个包来注册MediatR和Handlers,使用ASP.Net Core DI服务(实际上是接口(interface)IServiceCollection
,实现在 Microsoft.Extensions.DependencyInjection
中并且不限于仅在 ASP.Net Core 中使用)。
MediatR.Extensions.Microsoft.DependencyInjection
Link to NuGet Package information .
可以找到介绍该包及其功能的博客文章 here
直接从(非常短的)博文复制的注册示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMediatR(typeof(Startup));
}
此包执行多项功能以启用 MediatR,包括所需的处理程序程序集扫描:
You can either pass in the assemblies where your handlers are, or you can pass in Type objects from assemblies where those handlers reside. The extension will add the IMediator interface to your services, all handlers, and the correct delegate factories to load up handlers. Then in your controller, you can just use an IMediator dependency:
public class HomeController : Controller
{
private readonly IMediator _mediator;
public HomeController(IMediator mediator)
{
_mediator = mediator;
}
public IActionResult Index()
{
var pong = _mediator.Send(new Ping {Value = "Ping"});
return View(pong);
}
}
关于c# - MediatR 与 ASP.NET Core DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35409924/