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.?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With