在 ASP.NET MVC 4 中使用 Unity - 依赖注入错误

Using Unity in ASP.NET MVC 4 - Dependency injection error

我正在尝试使用 Unity 将依赖项注入网络 api 控制器。

我关注了

http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection

很接近,但是我在实例化构造函数时仍然出错,没有无参数构造函数。

控制器:

public class ContactsController : ApiController
    {
        IContactsRepository repository;

        public ContactsController(IContactsRepository repository)
        {
            this.repository = repository;
        }

        public List<ContactDTO> GetAllContacts()
        {
            return repository.GetAllContacts().ToList();
        }
    }

存储库接口和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();
                }
            }
        }
    }

我添加了这行:

Bootstrapper.Initialise();

Global.asax 文件,并在 Bootstrapper.cs 中添加:

container.RegisterType<IContactsRepository, ContactsRepository>();

然而,当我尝试通过 url 访问联系人时,出现错误:

An error occurred when trying to create a controller of type 'ContactsController'. Make sure that the controller has a parameterless public constructor.

我是不是漏掉了什么?

我看到您正在使用 ApiController - 因为 WebAPI 依赖注入是以不同的方式实现的。您指的是解决依赖关系的标准 MVC 方法,它不适用于 WebAPI。

您需要安装 Unity.WebAPI 包才能正常工作 NuGet