1

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?

6
  • 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.... Commented Jun 17, 2015 at 10:45
  • yes, the Bootstrapper.Initialise(); is doing that work Commented Jun 17, 2015 at 10:47
  • This is the package from nuget that you should be using Commented Jun 17, 2015 at 10:47
  • See, there should be no initialise because it is bootstrapped when the application is loaded - not when the global.asax is ran Commented Jun 17, 2015 at 10:48
  • Uhm.. I might be underthinking this, but just add an empty, parameterless ctor? Commented Jun 17, 2015 at 10:50

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.