asp.net-mvc - ASP.NET MVC WebApi : No parameterless constructor defined for this object

标签 asp.net-mvc asp.net-web-api ninject unit-of-work

我有一个 ASP.NET MVC 4 应用程序,我想实现工作单元模式。

在我的网络项目中,我有:

IocConfig.cs

using System.Web.Http;
using NinjectMVC.Data;
using NinjectMVC.Data.Contracts;
using Ninject;


namespace NinjectMVC
{
    public class IocConfig
    {
        public static void RegisterIoc(HttpConfiguration config)
        {
            var kernel = new StandardKernel(); // Ninject IoC

            // These registrations are "per instance request".
            // See http://blog.bobcravens.com/2010/03/ninject-life-cycle-management-or-scoping/

            kernel.Bind<RepositoryFactories>().To<RepositoryFactories>()
                .InSingletonScope();

            kernel.Bind<IRepositoryProvider>().To<RepositoryProvider>();
            kernel.Bind<INinjectMVCUow>().To<NinjectMVCUow>();

            // Tell WebApi how to use our Ninject IoC
            config.DependencyResolver = new NinjectDependencyResolver(kernel);
        }
    }
}

全局.asax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace NinjectMVC
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

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

            // Tell WebApi to use our custom Ioc (Ninject)
            IocConfig.RegisterIoc(GlobalConfiguration.Configuration);   

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

PersonsController.cs

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NinjectMVC.Data.Contracts;
using NinjectMVC.Model;

namespace NinjectMVC.Controllers
{
    public class PersonsController : ApiControllerBase
    {
        public PersonsController(INinjectMVCUow uow)
        {
            Uow = uow;
        }

        #region OData Future: IQueryable<T>
        //[Queryable]
        // public IQueryable<Person> Get()
        #endregion

        // GET /api/persons
        public IEnumerable<Person> Get()
        {
            return Uow.Persons.GetAll()
                .OrderBy(p => p.FirstName);
        }

        // GET /api/persons/5
        public Person Get(int id)
        {
            var person = Uow.Persons.GetById(id);
            if (person != null) return person;
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }

        // OData: GET /api/persons/?firstname=\'Hans\''
        // With OData query syntax we would not need such methods
        // /api/persons/getbyfirstname?value=Joe1
        [ActionName("getbyfirstname")]
        public Person GetByFirstName(string value)
        {
            var person = Uow.Persons.GetAll()
                .FirstOrDefault(p => p.FirstName.StartsWith(value));

            if (person != null) return person;
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }

        // Update an existing person
        // PUT /api/persons/
        public HttpResponseMessage Put(Person person)
        {
            Uow.Persons.Update(person);
            Uow.Commit();
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }

    }
}

当我尝试冲浪时:http://www.domain.com/Persons/Get我得到:

没有为此对象定义无参数构造函数。

有什么我错过的东西吗?我将不胜感激任何帮助。

以下是该项目的 zip 文件,以便更好地引用:

http://filebin.ca/E6aoOkaUpbQ/NinjectMVC.zip

最佳答案

Wep.API 使用与 MVC 框架不同的 IDependencyResolver

当您使用HttpConfiguration.DependencyResolver时,它仅适用于ApiController。但是您的 ApiControllerBase 派生自 Controller...

所以你的ApiControllerBase应该继承自ApiController

在 ApiBaseController.cs 中更改它:

public abstract class ApiControllerBase : ApiController
{
}

如果您想将依赖项注入(inject)到常规 Controller 派生类,您需要使用(在 IocConfig 中):

System.Web.Mvc.DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(container));

请注意,在这种情况下,您无法使用 NinjectDependencyResolver,因为它用于 ApiControllers

因此,您需要一个不同的NinjectMvcDependencyResolver,它应该实现System.Web.Mvc.IDependencyResolver

public class NinjectMvcDependencyResolver: NinjectDependencyScope,
                                           System.Web.Mvc.IDependencyResolver
{
    private IKernel kernel;

    public NinjectDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        this.kernel = kernel;
    }
}

关于asp.net-mvc - ASP.NET MVC WebApi : No parameterless constructor defined for this object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217636/

相关文章:

ajax - 如何将 Html.BeginForm 变成 Ajax.BeginForm

c# - 每个表一个存储库还是每个功能部分一个?

c# - 使用逗号分隔数值的表中的 POST 和 PUT 问题

c# - 如何获取请求查询字符串值?

c# - 如何编写自定义@Html.Control For(o => o.Property)?

asp.net-mvc - Azure ACS + MVC + WCF

c# - Ninject 和 ASP.NET Identity 2.0

c# - Ninject.Web.Common 和 Ninject.Mvc 未将 DependencyResolver 设置为使用 NinjectDependencyResolver

c# - 使用 HttpClient 时如何在 HttpContent 中设置大字符串?

c# - .NET 标准 + .NET 框架 : could not load file or assembly 'Ninject'