Had*_*des 20 c# dependency-injection ninject asp.net-web-api asp.net-web-api2
我在WebAPI项目中安装了以下软件包及其依赖项:
Ninject.Web.WebApi
Ninject.Web.WebApi.OwinHost
我这纯粹是作为web-api项目运行的.没有MVC.
当我运行我的应用程序并发POST
送到AccountController的Register操作时,我得到以下错误:
{
"message":"An error has occurred.",
"exceptionMessage":"An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.",
"exceptionType":"System.InvalidOperationException",
"stackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()",
"innerException":{
"message":"An error has occurred.",
"exceptionMessage":"Type 'RPT.Api.Controllers.AccountController' does not have a default constructor",
"exceptionType":"System.ArgumentException",
"stackTrace":" at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我,因为我可以在Google上找到的唯一细节似乎是从2012年开始.
注意:我也尝试过AutoFac而不是Ninject并在那里也遇到同样的错误.最令人沮丧的.
这是我的NinjectWebCommon.cs:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using RPT.Data;
using RPT.Services;
using RPT.Services.Interfaces;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(RPT.Api.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(RPT.Api.NinjectWebCommon), "Stop")]
namespace RPT.Api
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<RptContext>().ToSelf();
kernel.Bind<IUserStore<IdentityUser>>().To<UserStore<IdentityUser>>();
kernel.Bind<UserManager<IdentityUser>>().ToSelf();
kernel.Bind<IAccountService>().To<AccountService>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的AccountController:
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.ModelBinding;
using Microsoft.AspNet.Identity;
using RPT.Api.Models;
using RPT.Services.Interfaces;
namespace RPT.Api.Controllers
{
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
#region Initialisation
private readonly IAccountService _accountService;
public AccountController(IAccountService accountService) : base()
{
_accountService = accountService;
}
#endregion
#region Actions
[AllowAnonymous]
[Route("register")]
public async Task<IHttpActionResult> Register(UserRegistrationViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _accountService.RegisterUser(model.UserName, model.Password);
var errorResult = GetErrorResult(result);
return errorResult ?? Ok();
}
#endregion
#region Internal
protected override void Dispose(bool disposing)
{
if (disposing)
{
_accountService.Dispose();
}
base.Dispose(disposing);
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (result.Succeeded) return null;
if (result.Errors != null)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
#endregion
}
}
Run Code Online (Sandbox Code Playgroud)
Dea*_*ard 19
你修改OWIN Startup
类调用app.UseNinjectWebApi
和app.UseNinjectMiddleware
而不是调用app.UseWebApi
?
Ninject Web API示例中的Startup.cs执行此操作...
Viv*_*Dev 13
在我的情况下,原因是解析器无法找到映射.假设HomeController依赖于IDumb,解析器无法使用实现IDumb找到Dumb的具体实现.换句话说,错误消息
**No parameterless constructor defined for this object
An error occurred when trying to create a controller of type 'ToDoListT1.WebApp.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor**
Run Code Online (Sandbox Code Playgroud)
完全是误导.在我的情况下,我刚刚通过添加对Dumb类的项目的引用来解决.它应该是"没有找到IDumb的映射.".我不确定问题出在NInject或MS上.什么花了我几个小时来找到这个.
对我有用的是添加 NuGet 包,Ninject.Web.WebApi.WebHost
如下所述: https: //github.com/ninject/Ninject.Web.WebApi/wiki/Setting-up-an-mvc-webapi-application
归档时间: |
|
查看次数: |
29863 次 |
最近记录: |