Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject dependencies in a WebAPI with Unity

I have a WebAPI controller that (should) looks like this:

public class MyController : ApiController
{
    private IRepository repository;

    public MyController(IRepository repository) 
    {
        this.repository = repositor;
    }

    // REST implementations
}

WebApiConfig is configured like that:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Unity configuration
        var container = new UnityContainer();
        container
            .RegisterType<IRepository , CustomRepository>();
        config.DependencyResolver = new UnityResolver(container);

        // Web API routes
        // CORS
    }
}

then in Global.asax.cs I have something like:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    // CORS
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // some CORS config
    } 
}

and finally I have a Startup.cs:

[assembly: OwinStartup(typeof(Path.To.Startup))]
namespace ZeroCode.ConfigurazioneServizio.Web.Api
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            new Mapping().Bootstrap();
        }
    }
}

To me everything looks ok, the code builds and I can launch the controller but as soon I make a request I get error cause parameterless constructor isn't present. So I've added the default constructor but this will instantiate the controller so IRepository will never be injected.

I've searched for a possible solution. One of them tried to implement IHttpControllerActivator and so i've realized something like this:

public class UnityHttpControllerActivator : IHttpControllerActivator
{
    private IUnityContainer _container;

    public UnityHttpControllerActivator(IUnityContainer container)
    {
        _container = container;
    }

    public IHttpController Create(System.Net.Http.HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        return (IHttpController)_container.Resolve(controllerType);
    }
}

At this point I've modified the WebApiConfig.cs inserting this line

config.Services.Replace(typeof(IHttpControllerActivator), new UnityHttpControllerActivator(container));

right after the config.DependencyResolver but this doesn't resolve the issue and exception is raised inside the Create method. I don't know what else I can do.

like image 300
BAD_SEED Avatar asked Nov 28 '22 13:11

BAD_SEED


2 Answers

There's a nice little Nuget Package - Unity.Webapi. If you add that, you can simply plug in your container into your HttpConfiguration

public static void Register(HttpConfiguration config)
{
    // Unity configuration
    var container = new UnityContainer();
    container.RegisterType<IRepository , CustomRepository>();
    config.DependencyResolver = new UnityResolver(container);

    //this
    config.DependencyResolver = new UnityDependencyResolver(container);

    // Web API routes
    // CORS
}

Then you can bypass the extra class and web.config changes.

like image 155
Jonesopolis Avatar answered Dec 07 '22 19:12

Jonesopolis


The first answer states to add Unity.WebApi. It is correct. After adding this package use it as is described in this link Using Unity.Mvc5 and Unity.WebApi together in a project. I did like this and my problem was solved.

like image 36
Harry .Naeem Avatar answered Dec 07 '22 18:12

Harry .Naeem