尝试创建 'XXXXController' 类型的控制器时出错。确保控制器具有无参数 public 构造函数

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

我创建了一个 asp.net web api 项目并在 AccountController 中实现了以下 HTTP GET 方法,在 AccountService 中实现了相关的服务方法和存储库方法 & AccountRepository分别。

// WEB API 
public class AccountController : ApiController
{
    private readonly IAccountService _accountService;

    public AccountController(IAccountService accountService)
    {
        _accountService = accountService;
    }

    [HttpGet, ActionName("UserProfile")]
    public JsonResult<decimal> GetUserSalary(int userID)
    {
        var account = _accountService.GetUserSalary(userID);
        if (account != null)
        {
            return Json(account.Salary);
        }
        return Json(0);
    }
}

服务/业务层

public interface IAccountService
{
    decimal GetUserSalary(int userId);
}

public class AccountService : IAccountService
{
    readonly IAccountRepository _accountRepository = new AccountRepository();

    public decimal GetUserSalary(int userId)
    {
        return _accountRepository.GetUserSalary(userId);
    }
}

存储库/数据访问层

public interface IAccountRepository
{
    decimal GetUserSalary(int userId);
}

public class AccountRepository : IAccountRepository
{
    public decimal GetUserSalary(int userId)
    {
        using (var db = new AccountEntities())
        {
            var account = (from b in db.UserAccounts where b.UserID == userId select b).FirstOrDefault();
            if (account != null)
            {
                return account.Salary;
            }
        }
        return 0;
    }
}

UnityConfig

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        container.RegisterType<IAccountService, AccountService>();
        container.RegisterType<IAccountRepository, AccountRepository>();
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

但是当我调用 API 方法时 GetUserSalary() 我收到一条错误消息

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

您当前的构造函数有参数(如果您愿意,也可以是 args)。

见:

public AccountController(IAccountService accountService)
{
    _accountService = accountService;
}

All you need to do is add a "Parameter-less Constructor" into the controller as well.

public AccountController()
{
}

无参数构造函数通常高于有参数的构造函数,但据我所知,这只是由于标准而不是它可能导致的任何实际效果。

There is also an already existing issue/question similar to this I will link below that may provide further details.

Make sure that the controller has a parameterless public constructor error

检查您是否没有忘记注册 Unity IoC 容器本身:

  • 如果您使用 ASP.NET 框架,它可以是 - Global.asax 或 Startap.cs (Owin) 通过 UnityConfig.RegisterComponents() 方法。
  • 如果您使用 ASP.NET 核心,那么在 Startup.cs 文件中(我无法找到其配置的官方指南)