How to use dependency injection in an ASP.NET Web API 2 controller using Unity?

Viewed 864

In Visual Studio 2019, I created an ASP.NET Web API project. I created a Web API 2 controller. I followed this link 1 and link 2 to implement dependency injection using Unity.

I have shared the code according to link 1 but it is not working. I get an error in method GetService(Type serviceType) of UnityResolver (which I copied from first link).

Error is:

Exception thrown: 'Unity.ResolutionFailedException' in Unity.Container.dll

I checked this using breakpoints. It is returning null although container is not null.

I have been searching this so long. I don't understand where it is wrong or I did something wrong.

I am new to .NET Framework and also to programming. Any help or advice appreciated.

public object GetService(Type serviceType)
{
        try
        {
            return container.Resolve<Type>();
            //return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
}

MyAPIController.cs

public class MyAPIController : ApiController
{
    private IAgent agent;

    public MyAPIController (IAgent _agent)
    {
        this.agent= _agent;
    }

    [HttpPost]
    [Route("AgentService")]
    public string GetAgentServices([FromBody] InputData inputData)
    {
      return "nothing";
    }
 }

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var container = new UnityContainer();
        container.RegisterType<IAgent, Agent>();
        config.DependencyResolver = new UnityResolver(container);
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}
0 Answers
Related