Unity container ResolutionFailedException ASP.NET Web API 2

Viewed 196

I have a ASP.Net application using Unity 5.11 which setup in the standard way.

Using a UnityResolver implementing IDependencyResolver, although i am getting a lot of exception on GetService.

I am currently ignoring certain Interfaces on which I do not inject as you will see in the code. I am not particularly happy with the approach below, is there any way to stop Unity / ASP.net requesting these interfaces to be injected from Unity?

As a note all my dependencies are all injected perfectly fine, just wondered if there was a way to stop these exception being thrown, as i would expect it to have some kind of performance detriment.

public class UnityResolver : IDependencyResolver
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// 
    /// </summary>
    protected IUnityContainer container;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="container"></param>
    public UnityResolver(IUnityContainer container)
    {
        Log.Info($"Initializing a container");
        this.container = container ?? throw new ArgumentNullException("container");
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException ex)
        {
            var msgToLower = ex.Message.ToLowerInvariant();
           
            if (!msgToLower.Contains("ihttpcontrollerselector") &&
                !msgToLower.Contains("ihttpcontrolleractivator") &&
                !msgToLower.Contains("ihttpactionselector") && 
                !msgToLower.Contains("ihttpactioninvoker") && 
                !msgToLower.Contains("icontentnegotiator") && 
                !msgToLower.Contains("iexceptionhandler") && 
                !msgToLower.Contains("modelmetadataprovider") && 
                !msgToLower.Contains("imodelvalidatorcache") && 
                !msgToLower.Contains("iapioutputcache") && 
                !msgToLower.Contains("icachekeygenerator")) 
            {
                Log.Error($"Get service entity {serviceType.Name} failed {ex.Message}");
            }
            return null;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="serviceType"></param>
    /// <returns></returns>
    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException ex)
        {
            Log.Error($"Get services entity failed {ex.Message}");
            return new List<object>();
        }
    }


    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    /// <summary>
    /// 
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        container.Dispose();
    }
}

For completeness

I setup Unity from Global.asax.cs

protected void Application_Start()
{

   GlobalConfiguration.Configure(WebApiConfig.Register);
   GlobalConfiguration.Configure(UnityConfig.RegisterComponents);

   ....
}

And now my UnityConfig.cs

public static void RegisterComponents(HttpConfiguration config)
{
   //Dependency container
   var container = new UnityContainer();

   ... register my Types, Singletons etc

   config.DependencyResolver = new UnityResolver(container);
}

And a test controller

[RoutePrefix("api/testing")]
public class TestController : ApiController
{
    private readonly IDatabaseConfigService _dbConfigService;
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// Test controller
    /// </summary>
    public TestController(IDatabaseConfigService dbConfigService)
    {
        _dbConfigService = dbConfigService;
    }
}

A few of the exception messages are below when I remove the string comparison.

2020-07-24 08:06:37,092 [12] ERROR Api.Containers.UnityResolver [GetService Api.Containers.UnityResolver] - Get service entity IHostBufferPolicySelector failed The current type, System.Web.Http.Hosting.IHostBufferPolicySelector, is an interface and cannot be constructed. Are you missing a type mapping?


Exception occurred while: • while resolving: IHostBufferPolicySelector

2020-07-24 08:06:37,117 [12] ERROR Api.Containers.UnityResolver [GetService Api.Containers.UnityResolver] - Get service entity IHostBufferPolicySelector failed The current type, System.Web.Http.Hosting.IHostBufferPolicySelector, is an interface and cannot be constructed. Are you missing a type mapping?


Exception occurred while: • while resolving: IHostBufferPolicySelector

2020-07-24 08:07:07,201 [43] ERROR Api.Containers.UnityResolver [GetService Api.Containers.UnityResolver] - Get service entity IContentNegotiator failed The current type, System.Net.Http.Formatting.IContentNegotiator, is an interface and cannot be constructed. Are you missing a type mapping?


Exception occurred while: • while resolving: IContentNegotiator

2020-07-24 08:07:07,403 [41] ERROR Api.Containers.UnityResolver [GetService Api.Containers.UnityResolver] - Get service entity IExceptionHandler failed The current type, System.Web.Http.ExceptionHandling.IExceptionHandler, is an interface and cannot be constructed. Are you missing a type mapping?


Exception occurred while: • while resolving: IExceptionHandler

0 Answers
Related