C# ResolveDependencies使用c为特定服务返回null#

C# ResolveDependencies使用c为特定服务返回null#,c#,asp.net,asp.net-web-api,unity-container,C#,Asp.net,Asp.net Web Api,Unity Container,我有一个用c#编写的web api应用程序,我使用app insights记录异常,因此我注册了一个服务,如下所示: private IExceptionLogService ExceptionLogService { get; set; } 这也是unity配置中的寄存器 <register type="IExceptionLogService" mapTo="ExceptionLogService" /> 但当我试图解析依赖项时,它返回null private void Re

我有一个用c#编写的web api应用程序,我使用app insights记录异常,因此我注册了一个服务,如下所示:

private IExceptionLogService ExceptionLogService { get; set; }
这也是unity配置中的寄存器

<register type="IExceptionLogService" mapTo="ExceptionLogService" />
但当我试图解析依赖项时,它返回null

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

这里有什么问题?

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

您应该提供自己的
idependencysolver
实现,该实现封装了
UnityContainer
,或者使用一些现有的实现。本文描述了示例实现

我建议使用NuGet包

将此NuGet添加到项目后,将添加class
UnityConfig
。将您的注册放到它的
RegisterComponents()
方法中,并添加以下对
应用程序的调用\u Start()


UnityConfig.RegisterComponents()

ExceptionLogService
后面是否没有任何InneException。没有
private void ResolveDependencies(HttpConfiguration configuration)
{
    ExceptionLogService = ExceptionLogService ?? (IExceptionLogService)configuration.DependencyResolver.GetService(typeof(IExceptionLogService));
}