Ninject不使用Asp.Net WebApi

时间:2015-03-08 01:54:17

标签: asp.net-mvc-5 ninject asp.net-web-api2

我见过很多人问过这个问题并尝试了他们接受的答案,但没有一个人对我有用。

当我尝试将Ninject与我的asp.net webapi

一起使用时,我一直收到此错误
 { "Message": "An error has occurred.", "ExceptionMessage": "An error
 occurred when trying to create a controller of type
 'SubjectPostsController'. 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)\ \ at
System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage
request)\ \ at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext ()",
"InnerException": { "Message": "An error has occurred.",
"ExceptionMessage": "Type
'Analyzer.Controllers.SubjectPostsController' does not have a default
 constructor", "ExceptionType": "System.ArgumentException",
"StackTrace": " at System.Linq.Expressions.Expression.New(Type type)\
\ at System.Web.Http.Internal.TypeActivator.Create[TBase](Type
instanceType)\ \ atSystem.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage
request, Type controllerType, Func`1& activator)\ \ at  System.Web.Http.Dispatcher.DefaultHttpControllerActivator.CreateHttpRequestMessa ge
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType)" } }

我的控制器:

using Analyzer.Models.ModelsForApp;
using Analyzer.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Analyzer.Controllers
{
    public class SubjectPostsController : ApiController
    {
        private IRepository _repo;
        public SubjectPostsController(IRepository repo)
        {
            _repo = repo;
        }
        public IEnumerable<SubjectPost> Get()
        {
            var posts = _repo.GetSubjectPosts()
           .OrderByDescending(p =>p.Created).ToList();
            return posts;

        }
    }
}

Ninject.WebCommon:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof  Analyzer.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof (Analyzer.App_Start.NinjectWebCommon), "Stop")]

namespace Analyzer.App_Start
{
    using System;
    using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using Analyzer.Database;
using Analyzer.Repository;
using System.Web.Http;


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<ApplicationDbContext>().To<ApplicationDbContext>().InRequestScope();
        kernel.Bind<IRepository>().To<Repository>().InRequestScope();
    }        
}

}

我安装的nuget包是:

Ninject version 3.2.2.0
Ninject integration for WepApi2 3.2.4.0
Ninject Web Host for WebApi2 3.2.4.0
Ninject.MVC3 3.2.1.0
Ninject.Web 3.2.1.0
Ninject.Web.Common 3.2.3.0
Ninject.Web.Common.WebHost 3.2.3.0
WebApiContrib.IoC.Ninject

到目前为止,我已经尝试了很多可能性, 尝试该方法时,GlobalConfiguration.Configuration.DependencyResolver会抛出异常。

所以基本上,我的想法已经用完了。有谁知道如何解决这个问题?

更新:我尝试使用Unity解决这个问题,但它确实有效。虽然我不知道使用统一的缺点和它获得的支持量(它似乎近一年没有更新)。更多关于团结的研究,但我仍然对使用Ninject的解决方案感兴趣。

更新2:它也适用于SimpleInjector ......我开始认为问题来自Ninject。任何人都可以让Ninject使用WebApi吗?

1 个答案:

答案 0 :(得分:1)

我使用以下内容:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        var dependencyInjectionProvider = new DependencyInjectionProvider();

        // Set MVC depencendy resolver for asp mvc web project
        DependencyResolver.SetResolver(dependencyInjectionProvider.GetMvcDependencyResolver());

        // Set MVC depencendy resolver for asp mvc web API project
        GlobalConfiguration.Configuration.DependencyResolver = dependencyInjectionProvider.GetHttpDependencyResolver();


        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

DependencyInjectionProvider有两个内部组件:

  • HttpDependencyResolver解决了对ApiControlelrs的注射
  • MvcDependencyResolver解决对Mvc控制器的注射问题

您可以在https://gist.github.com/remojansen/d907f8e2c2c4bfb7f65e

找到完整的实施方案