简体   繁体   English

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

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

I'm trying to inject a dependency into a web api controller using Unity. 我正在尝试使用Unity将依赖项注入Web api控制器。

I followed 我跟着

http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection 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: Global.asax文件,并在Bootstrapper.cs添加:

container.RegisterType<IContactsRepository, ContactsRepository>();

However when i try to access contacts through the url I get the error: 但是,当我尝试通过url访问联系人时,出现错误:

An error occurred when trying to create a controller of type 'ContactsController'. 尝试创建类型为“ 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. 我看到您正在使用ApiController -WebAPI依赖项注入以不同的方式实现。 You are referring to a standard MVC way of resolving dependencies, which won't work for WebAPI. 您指的是解决依赖关系的标准MVC方法,该方法不适用于WebAPI。

You need to install Unity.WebAPI package to get it working NuGet 你需要安装Unity.WebAPI包,使其能工作的NuGet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM