Internal Server Error 500 Asp.net WebApi trying to DI with Entity

asp.net asp.net-mvc asp.net-mvc-5 asp.net-web-api entity-framework-6

Question

I am building an ASP.net WebApi, and trying to use Entity alongside. I am following this guide.

Getting Started with ASP.NET Web API 2 (C#)

I am receiving a 500 internal server error using Fiddler. The JSON Exception message states ExceptionMessage=An error occurred when trying to create a controller of type 'LocationsController'. Make sure that the controller has a parameterless public constructor.

Here is the Controller.cs

[RoutePrefix("api/Locations")]
public class LocationsController : ApiController
{
    // GET api/<controller>
    private IlocationsRepository LocationsRepo;

    public LocationsController(IlocationsRepository _repo)
    {
        if (_repo == null) { throw new ArgumentNullException("_repo"); }
        LocationsRepo = _repo;
    }

    [HttpGet]
    [Route("")]
    public IEnumerable<Location> GetAll()
    {
       return LocationsRepo.GetAll();
    }
}

I can't use a parameterless public constructor because I need to use the Database Repository that was created for Locations. I verified the issue was with the IlocationsRepository by doing the following.

When I replace the LocationsController constructor with no parameters , and declare a List<Location> within the controller, and use dummy data. I receive a 200 with all the json data correct.

Here is the start of the Global.asax.cs file

 public class Global : System.Web.HttpApplication
 {
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    protected void Session_Start(object sender, EventArgs e)
    {

    }
 }

It seems as if I need to do the dependency injection in the Global, but none of the guides had any information regarding this part.

For posterity here is the ContextDB cs

public class WebServerContext : DbContext
{
    public WebServerContext() : base("WebServerContext") {}
    public DbSet<Order> dOrders { get; set; }
    public DbSet<Location> dLocations { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

For additional posterity, here is the Locations Repository.

public class LocationsRepository : IlocationsRepository
{
    private z_Data.WebServerContext db = new z_Data.WebServerContext();

    public void Add(Location item)
    {
        db.dLocations.Add(item);
    }
    public IEnumerable<Location> GetAll()
    {
        return db.dLocations;
    }
}
1
0
6/25/2016 10:41:46 PM

Accepted Answer

As per Dependency Injection for Web Api tutorial on MSDN, you are missing the line to register the dependency resolver (a concrete class that implements System.Web.Http.IDependencyResolver) with Web Api. It acts like a bridge between your DI container and Web Api so it can resolve your constructor dependencies.

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container); // <- You need this

    // Other Web API configuration not shown.
}

Of course, that assumes you are using Unity. If not, you should either use the DependencyResolver that came with your DI container or implement your own.

NOTE: With some DI containers, you also need to register all of your controllers explicitly.

4
6/25/2016 11:01:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow