c# - 在其他服务中访问 MVC DI 服务

标签 c# asp.net-core .net-core asp.net-core-webapi asp.net-core-2.0

我正在构建一个 HealthAPI 类库,它为我们的 HealthMonitor 服务提供统计信息列表。

我已经成功地完成了这项工作,中间件正在记录服务启动时间并记录响应时间,我们的运行状况监视器能够通过调用我们的StatusController来解析这些值。其中有许多返回 IActionResult JSON 响应的操作。

我们打算在所有服务中重用它,因此选择将 API Controller 与 DI 服务和中间件一起保留在类库中,以使 Controller 可访问,我最初执行了以下操作。

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("HealthApiLibrary"))); //Bring in the Controller for HealthAPI;
    services.AddSingleton<HealthApiService>();
}

但是在重构阶段,我想通过执行以下操作来稍微清理一下:

1) 重构 services.AddSingleton<HealthApiService>();进入services.AddHealthApi(); (我们还没有为此做任何工作,但在回答这个问题时仍然可能相关)

2) 作为 services.AddHealthApi(); 的一部分加载到我的 StatusController 中打电话。

我尝试过以下方法:

public class HealthApiService
{
    public HealthApiService(IMvcBuilder mvcBuilder)
    {
        mvcBuilder.AddApplicationPart(Assembly.Load(new AssemblyName("HealthApiLibrary"))); //Bring in the Controller for HealthAPI

        ResponseTimeRecords = new Dictionary<DateTime, int>();
        ServiceBootTime = DateTime.Now;
    }

    public DateTime ServiceBootTime { get; set; }
    public Dictionary<DateTime,int> ResponseTimeRecords { get; set; }
    public string ApplicationId { get; set; }
}

但是这只会产生以下错误:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.DependencyInjection.IMvcBuilder' while attempting to activate 'HealthApiLibrary.Services.HealthApiService'.

最佳答案

<强>1。依赖注入(inject)

您收到异常是因为服务集合中没有注册 IMvcBuilder。我将这种类型添加到集合中是没有意义的,因为它仅在启动期间使用。

<强>2。扩展方法

您可以创建一个扩展方法来实现您想要的方法。

public static class AddHealthApiExtensions
{
    public static void AddHealthApi(this IServiceCollection services)
    {
        services.AddSingleton<HealthApiService>();
    }
}

<强>3。程序集.加载

看看@Tseng 的评论。

关于c# - 在其他服务中访问 MVC DI 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601507/

相关文章:

c# - 使用 EF Core 时异步调用比同步调用慢

c# - JSON 结果 : Expected ',' instead of ''

c# - 承载错误 ="invalid_token", error_description ="The issuer is invalid"

c# - 上传到 AWS S3 时无法访问已关闭的流

asp.net-core - 如何设置 Application Insights for .NET Core 的 cloud_roleName?

c# - 堆栈 - 值类型的值存储在哪里?

c# - 我如何为 json 属性返回 null 而不是 "data": []

c# - 如何在不使用 "new"关键字的情况下启动一个类?

c# - 当我的 Xamarin 应用程序仅在 Release模式下中断时,我该如何调试它?

c# - 增加使用 Azure 部署的 K8s 集群中的最大文件上传大小(使用 C# 和 React 的 ASP.NET Core 中的项目)