1
votes

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?

1
Unity usually has a class that is called when the application is loaded and is put in the app start? Basically I think you havent set your dependency resolver to use unity... so when the resolver tries to resolve the controller it can't.... - Callum Linington
yes, the Bootstrapper.Initialise(); is doing that work - Mefhisto1
This is the package from nuget that you should be using - Callum Linington
See, there should be no initialise because it is bootstrapped when the application is loaded - not when the global.asax is ran - Callum Linington
Uhm.. I might be underthinking this, but just add an empty, parameterless ctor? - Nicklas Pouey-Winger

1 Answers

2
votes

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