I'm trying to inject a dependency into a web api controller using Unity.
I followed
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection
closely, however I still get error while instantiating constructor, there there's no parameterless constructor.
Controller:
public class ContactsController : ApiController
{
IContactsRepository repository;
public ContactsController(IContactsRepository repository)
{
this.repository = repository;
}
public List<ContactDTO> GetAllContacts()
{
return repository.GetAllContacts().ToList();
}
}
Repository interface and class:
public interface IContactsRepository
{
IEnumerable<ContactDTO> GetAllContacts();
}
Class:
public class ContactsRepository : IContactsRepository
{
public IEnumerable<ContactDTO> GetAllContacts()
{
using (var db = new ContactDatabaseEntities())
{
foreach (var contact in db.Contacts)
{
yield return contact.Convert();
}
}
}
}
I added the line:
Bootstrapper.Initialise();
to Global.asax
file, and in Bootstrapper.cs
I added:
container.RegisterType<IContactsRepository, ContactsRepository>();
However when i try to access contacts through the url I get the error:
An error occurred when trying to create a controller of type 'ContactsController'. Make sure that the controller has a parameterless public constructor.
Am I missing something?
I see you are using
ApiController
- for WebAPI dependency injection is implemented in different way. You are referring to a standard MVC way of resolving dependencies, which won't work for WebAPI.You need to install Unity.WebAPI package to get it working NuGet