Search code examples
c#asp.netasp.net-web-apiunity-container

ResolveDependencies returns null for a specific service with c#


I am having a web api application written in c#, and i have used app insights to log the exceptions, so i have registered a service as follows,

private IExceptionLogService ExceptionLogService { get; set; }

and this is register inside the unity config as well,

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

but when i run the application, the configuration shows in debug as well, it shows the file and the assembly.

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

but when i try to resolve the dependencies it returns null

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

what is the issue here?


Solution

  • You register dependency in Unity DI container that implements IUnityContainer interface but trying to resolve dependency through HttpConfiguration.DependencyResolver of IDependencyResolver type. By default DependencyResolver is set to instance of System.Web.Http.Dependencies.EmptyResolver. It's clear from EmptyResolver class name that it's just a stub that performs no actual resolving.

    You should either provide your own implementation of IDependencyResolver that wraps UnityContainer or use some existing implementation. Sample implementation is described in article Dependency Injection in ASP.NET Web API 2.

    I suggest using of Unity.WebAPI NuGet package.

    After you add this NuGet to your project, class UnityConfig will be added. Put your registrations to its RegisterComponents() method and add following call to Application_Start():

    UnityConfig.RegisterComponents();