c# - MediatR 与 ASP.NET Core DI

标签 c# asp.net asp.net-core mediatr

我正在使用新的 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 GitHub Project .

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/

相关文章:

azure - 是否可以在不离线的情况下将 ASP.NET Core 网站部署到 Azure?

java - 使用本地过程将数据插入数据库或使用最近的框架(如 spring 或 Entity Framework )将数据插入数据库之间有什么区别吗?

c# - Debug.Assert 出现在 Release模式

c# - 无法将类型 'System.Numerics.BigInteger' 隐式转换为 'int' 。存在显式转换(您是否缺少转换?)

c# - ASP.NET 核心 : Error when using a custom DbContext while also using Identity

c# - 在 ASP.NET Core 6 中检查事件目录的跨平台方法

c# - XAML 布局更改未在生成时更新

c# - WebMatrix.WebData 无法从单独的 ASP.NET 应用程序读取成员资格信息

c# - 为什么使用 System.Runtime.Caching 或 System.Web.Caching 而不是静态变量?

c# - asp/mvc应用中使用错误提示