使用 c# 的特定服务的 ResolveDependencies returns null

ResolveDependencies returns null for a specific service with c#

我有一个用 c# 编写的 Web api 应用程序,我使用应用洞察记录异常,所以我注册了一个服务,如下所示,

private IExceptionLogService ExceptionLogService { get; set; }

这也是统一配置中的寄存器,

<register type="IExceptionLogService" mapTo="ExceptionLogService" />

但是当我 运行 应用程序时,配置也显示在调试中,它显示文件和程序集。

private static IUnityContainer BuildUnityContainer()
{
            var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            var container = new UnityContainer().LoadConfiguration(section);
            return container;
}

但是当我尝试解决依赖关系时它 returns null

private void ResolveDependencies(HttpConfiguration configuration)
{
    ExceptionLogService = ExceptionLogService ?? (IExceptionLogService)configuration.DependencyResolver.GetService(typeof(IExceptionLogService));
}

这里有什么问题?

您在实现 IUnityContainer 接口的 Unity DI 容器中注册依赖项,但试图通过 IDependencyResolver 类型的 HttpConfiguration.DependencyResolver 解析依赖项。默认情况下 DependencyResolver 设置为 System.Web.Http.Dependencies.EmptyResolver 的实例。从 EmptyResolver class 名称可以清楚地看出它只是一个不执行实际解析的存根。

您应该提供自己的 IDependencyResolver 实现来包装 UnityContainer,或者使用一些现有的实现。文章 Dependency Injection in ASP.NET Web API 2.

中描述了示例实现

我建议使用 Unity.WebAPI NuGet 包。

将此 NuGet 添加到项目后,将添加 class UnityConfig。将您的注册放入其 RegisterComponents() 方法并添加以下对 Application_Start() 的调用:

UnityConfig.RegisterComponents();