Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DependencyResolver in System.Web.Http.HttpConfiguration vs DependencyResolver in System.Web.Mvc

I am working on the new ASP.Net Web API project using Microsoft Unity as IoC container. I am a little confused which one is correct.

If I set the DependencyResolver of System.Web.Http.HttpConfiguration. Then I able to call my API controllers having dependency and the dependencies are being resolved by the Unity framework. But, for the MVC controller like HomeController Unity is not able to inject any dependency until I set the DependencyResolver in System.Web.Mvc.

API controller dependencies resolved but MVC Controller dependencies not. if I add the code below:

public class IocConfig
{
    public static void Register(HttpConfiguration config)
    {
        var container = UnityConfig.GetConfiguredContainer();
        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
        config.DependencyResolver = new UnityResolver(container);
        //DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

MVC Controller dependencies resolved successfully but API controller dependencies not. if I add the code below:(Un-comment the line)

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Just let you know that the project template is ASP.Net Web API and I am using Microsoft.Unity.

Should I set both DependencyResolver or am I doing something wrong.?

like image 620
ali Avatar asked Mar 15 '17 00:03

ali


1 Answers

If using both MVC and Web API in the same project, you would need to set both resolvers. If doing so in the same code location then distinguish the resolvers by prefixing their namespaces.

var container = UnityConfig.GetConfiguredContainer();

FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

//MVC
DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));
//Web API
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);

Note the namespaces used for the different DependencyResolver

like image 116
Nkosi Avatar answered Sep 17 '22 13:09

Nkosi