Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors while using custom dependency resolver with Unity and Web API controller

I am using following class as a dependency resolver. Got reference from http://www.asp.net/web-api/overview/advanced/dependency-injection

   public class UnityWebAPIResolver : IDependencyResolver
    {
    protected IUnityContainer container;

    public UnityWebAPIResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType); **// This line throws error**
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType); **// This line throws error**
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityWebAPIResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

In WebApiConfig class after route configuration i am configuring dependency resolver like this

config.DependencyResolver = new UnityWebAPIResolver(UnityConfig.GetContainer());

The problem is i am getting several errors like this..

InvalidOperationException - The type IHostBufferPolicySelector does not have an accessible constructor.
InvalidOperationException - The type ModelMetadataProvider does not have an accessible constructor.
InvalidOperationException - The type ITraceManager does not have an accessible constructor.
InvalidOperationException - The type ITraceWriter does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerSelector does not have an accessible constructor.
InvalidOperationException - The type IAssembliesResolver does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerTypeResolver does not have an accessible constructor.
InvalidOperationException - The type IHttpActionSelector does not have an accessible constructor.
InvalidOperationException - The type IActionValueBinder does not have an accessible constructor.
InvalidOperationException - The type IContentNegotiator does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerActivator does not have an accessible constructor.
InvalidOperationException - The type IBodyModelValidator does not have an accessible constructor.

Even if i try to do something like this in my global.asax i am getting same errors.

GlobalConfiguration.Configuration.DependencyResolver = new UnityWebAPIResolver(UnityConfig.GetContainer());

Question : All dependencies into my API Controller seems to be injected properly, my only concern is since it cannot resolve several of above mentioned (framework specific ) types, is there any chance that it can cause the whole framework malfunction and generate random errors ?

like image 723
ATHER Avatar asked Jan 16 '15 00:01

ATHER


People also ask

What is the web API dependency resolver?

But now there is a problem, because your application doesn't create the controller directly. Web API creates the controller when it routes the request, and Web API doesn't know anything about IProductRepository. This is where the Web API dependency resolver comes in. Web API defines the IDependencyResolver interface for resolving dependencies.

What is the scope of httpconfiguration dependency resolver?

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope. Web API then calls GetService on the child scope to create the controller.

How to resolve dependencies in Unity?

There could be more methods to resolve dependencies like property injection or a service locator. We used constructor injection in our application. One can make use of other containers instead of Unity.

How to use dependency injection in web API applications using Unity?

Using dependency injection in Web API applications using Unity 1 Create a new ASP.NET Web application 2 Install Unity through Nuget At the current time of writing the version used in the Package Manager Console was as follows: 1 PM> Install-Package Unity -Version 5.7.3 3 Create a new repository We add this to the Model folder. ... More items...


1 Answers

There is no problem and your program works as expected here. What you see are first-chance exceptions thrown by the Unity's Resolve method. The exception is thrown because Unity will never return null when a service can't be resolved. IDependencyResolver.GetService implementations however should always return null if the requested service is not registered in dependency resolver implementation.

If GetService returns null, MVC will fall back on the framework's default implementation for the requested service. In most cases there is no need to override those services in the Unity container, and even when a different service is required, you can easily replace MVCs default implementation without adding it to the Unity configuration at all.

But since Unity is expected to throw this exception, that's why those methods contain a catch clause. So the exception you are experiencing is caught in that method and null is returned.

Obviously it is very annoying to have the debugger stop at those methods many times after starting the application, so the solution is to mark those methods with the [DebuggerStepThrough] attribute, to prevent the debugger from stopping in these methods.

like image 188
Steven Avatar answered Sep 21 '22 08:09

Steven