error: Make sure that the controller has a parameterless public constructor webapi

error: Make sure that the controller has a parameterless public constructor webapi

我正在使用 webapi、unity 和 mvc。我收到错误 "Make sure that the controller has a parameterless public constructor"。我已经看到类似问题的解决方案,但仍然无法解决。我已经安装了 unity.webapi 并且似乎拥有所有必要的参考资料:

我已验证所有内容都与此站点上的内容相符:

http://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

这是我的:

引导程序:

public static class Bootstrapper
{
    public static IUnityContainer Initialise()
    {
        var container = BuildUnityContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();

        container.RegisterType<IDatabaseFactoryHouseDB, DatabaseFactoryHouseDB>(new HierarchicalLifetimeManager());
        container.RegisterType<UnitOfWorkHouseDB>();

        // repositories
        container.RegisterType<IEmployeeRepository, EmployeeRepository>();

        // services
        container.RegisterType<IEmployeeService, EmployeeService>();
        RegisterTypes(container);

        return container;
    }
    public static void RegisterTypes(IUnityContainer container) { }
}

Global.asax:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        Database.SetInitializer<HouseDBContext>(null);

        Bootstrapper.Initialise();
        //required for setting routes in the attributes of a controller method
        GlobalConfiguration.Configuration.EnsureInitialized();
    }
}

Api 控制器:

public class EmployeeApiController : ApiController
{
    private readonly IEmployeeService employeeService;

    public EmployeeApiController(IEmployeeService employeeService)
    {
        this.employeeService = employeeService;
    }

    // rest of controller
}

网络Api配置:

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // use json strings as the default return value for the app
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
    }

统一配置:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

不确定我错过了什么。

编辑: 我注意到我的 App_Start 文件夹中有一个 UnityConfig class。在查看 Sarathy 的评论后,我意识到它没有被调用。我在 global.asax 中注释掉了我的引导程序初始化并添加了行 UnityConfig.RegisterComponents(),所以现在我的 global.asax 看起来像这样:

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        UnityConfig.RegisterComponents();  //  <--- added
        AreaRegistration.RegisterAllAreas();

        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        Database.SetInitializer<HouseDBContext>(null);

        //Bootstrapper.Initialise(); <-- not using bootstrapper anymore
        //required for setting routes in the attributes of a controller method
        GlobalConfiguration.Configuration.EnsureInitialized();
    }
}

我的 UnityConfig 如下所示:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();    
        container.RegisterType<IDatabaseFactoryHouseDB, DatabaseFactoryHouseDB>(new HierarchicalLifetimeManager());
        //container.RegisterType<IUnitOfWork>();
        container.RegisterType<UnitOfWorkHouseDB>();

        // repositories
        container.RegisterType<IEmployeeRepository, EmployeeRepository>();

        // services
        container.RegisterType<IEmployeeService, EmployeeService>();

        GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    }
}

但我仍然遇到无参数构造函数错误。有趣的是,即使我添加了一个无参数构造函数:

    public class EmployeeApiController : ApiController
    {
        private readonly IEmployeeService employeeService;

        public EmployeeApiController()
            : base()
        {
        } 

        public EmployeeApiController(IEmployeeService employeeService)
        {
            this.employeeService = employeeService;
        }
}

使用unityconfig 方法时仍然出现错误。使用引导程序,我没有收到错误,但我的服务未初始化。

我完全糊涂了。不知何故,我觉得我在混合使用 MVC 和 WebApi,但事情没有正确解决...

编辑 2:

我查看了我的无参数构造函数错误的内部异常并注意到它提到了我的 IUnitOfWork class:

"Resolution of the dependency failed, type = \"AngularMVC.Controllers.EmployeeApiController\", name = \"(none)\".\r\nException occurred while: while resolving.\r\nException is: InvalidOperationException - The current type, AngularMVC.Models.Interfaces.IUnitOfWork, is an interface and cannot be constructed. Are you missing a type mapping?\r\n-----------------------------------------------\r\nAt the time of the exception, the container was:\r\n\r\n Resolving AngularMVC.Controllers.EmployeeApiController,(none)\r\n Resolving parameter \"employeeService\" of constructor AngularMVC.Controllers.EmployeeApiController(AngularMVC.Services.IEmployeeService employeeService)\r\n Resolving AngularMVC.Services.EmployeeService,(none) (mapped from AngularMVC.Services.IEmployeeService, (none))\r\n Resolving parameter \"unitOfWork\" of constructor AngularMVC.Services.EmployeeService(AngularMVC.Models.Repositories.IEmployeeRepository employeeRepository, AngularMVC.Models.Interfaces.IUnitOfWork unitOfWork)\r\n Resolving AngularMVC.Models.Interfaces.IUnitOfWork,(none)\r\n"

仅此:

public interface IUnitOfWork
{
    void Commit();
}

当我在 UnityConfig 中执行以下操作时:

        container.RegisterType<IUnitOfWork>();
        IUnitOfWork sm = container.Resolve<IUnitOfWork>();

我得到同样的错误说明 "The current type, AngularMVC.Models.Interfaces.IUnitOfWork, is an interface and cannot be constructed. Are you missing a type mapping?"

从您的代码中,我可以看出您正在使用 Unity 作为 IoC 容器。 IoC 容器将处理控制器 class 的初始化。

要使 IoC 容器创建控制器实例,您的控制器 class 需要有一个无参数 public 构造函数(也称为默认构造函数)。

public class EmployeeApiController : ApiController
{
    private readonly IEmployeeService employeeService;

    public EmployeeAPIController() : base()
    {
    }

    public EmployeeApiController(IEmployeeService employeeService)
    {
        this.employeeService = employeeService;
    }
}

更新 1:2015 年 2 月 18 日 从您的代码中我没有看到 IUnitOfWork 接口的实现。工作单元是在领域集中建模中广泛使用的模式。通常,工作单元模式与存储库模式一起使用。工作单元的目的是让多个存储库可以在同一个数据库上下文中工作。

根据您的代码,您注册了

//container.RegisterType<IUnitOfWork>();
container.RegisterType<UnitOfWorkHouseDB>();

但是,我认为您应该有这样的注册代码:(我假设 UnitOfWorkHouseDB 是 IUnitOfWork 的实现)

container.RegisterType<IUnitOfWork, UnitOfWorkHouseDB>();

类似于:(EmployeeRepository 是 IEmployeeRepository 的实现)

// repositories
container.RegisterType<IEmployeeRepository, EmployeeRepository>();

通常,当我使用工作单元和存储库模式时,我会做以下结构:

IUnitOfWork 接口

public interface IUnitOfWork
{
    void Commit();
}

IUnitOfWork 实现:

public class UnitOfWork : IUnitOfWork
{
    //DBContext could your own db context, or a interface, like IDatabaseFactoryHouseDB 
    private DBContext _ctx;

    public UnitOfWork(DbContext ctx)
    {
        _ctx = ctx;
    }

    private IEmployeeRepository _EmployeeRepository;
    public IEmployeeRepository EmployeeRepository
    {
        get { return _EmployeeRepository ?? (_EmployeeRepository = new EmployeeRepository(_ctx)); }
    }

    private ICustomerRepository _CustomerRepository;
    public ICustomerRepository CustomerRepository
    {
        get { return _CustomerRepository ?? (_CustomerRepository = new CustomerRepository(_ctx)); }
    }

    public void Commit()
    {
        _ctx.SaveChange();
    }
}