Web Api 2和Ninject - 不解决

时间:2014-01-14 12:11:30

标签: asp.net-web-api ninject

使用ninject几年(在基础级别)我很难在全新的解决方案中使用webapi2。这在我的带有webapi的mvc4应用程序中运行良好。

错误:

通常怀疑告诉你绑定不起作用

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
An error occurred when trying to create a controller of type 'TenantController'. Make sure that the controller has a parameterless public constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<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.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'AIControlPoint.Data.Api.Controllers.TenantController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</InnerException>
</Error>

webapi2控制器非常基础,如果我在无参数初始化时创建上下文,它可以工作

    public class TenantController : ApiController
    {
        private TenantConfigurationContext tenantContext;

        public TenantController(TenantConfigurationContext tenantContext)
        {
            this.tenantContext = tenantContext;

        }

        public List<TenantConfiguration> Get()
        {
            var tenants = (from t in tenantContext.TenantConfigurations
                           select t)
                           .ToList();

            return tenants;
        }
    }
}

我的NinjectWebCommon就是这个

[assembly: WebActivator.PreApplicationStartMethod(typeof(AIControlPoint.Data.Api.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(AIControlPoint.Data.Api.App_Start.NinjectWebCommon), "Stop")]

namespace AIControlPoint.Data.Api.App_Start
{
    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();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<TenantConfigurationContext>().To<TenantConfigurationContext>();
        }        
    }
}

我安装的nuget包是:ninject,ninject.mvc3,ninject.web.common,ninject.webapi.dependencyresolver

有没有人设法让这个工作?任何帮助将不胜感激。

由于 史蒂芬

1 个答案:

答案 0 :(得分:0)

您直接在控制器内创建了一个TenantConfigurationContext实例 这将是TenantConfigurationContext的强耦合。 如果任何TenantConfigurationContext的实现更改或 发布该组件的新版本,然后您必须更改控制器类本身。 依赖注入消除了紧耦合,使应用程序灵活,可重用。 您正在使用Ninject作为依赖框架,但您尝试实现它的方式有一些 问题。见以下步骤:

首先,您需要创建一个如下所示的接口和类:

public interface ITenantConfigurationContext
{
    List<TenantConfiguration> TenantConfigurations();
}
public class TenantConfigurationContext : ITenantConfigurationContext
{
    public List<TenantConfiguration> TenantConfigurations()
    {
        return (get data from DB here);
    } 
}

然后在Web Api控制器中调用ITenantConfigurationContext:

public class TenantController : ApiController
{
    private ITenantConfigurationContext tenantContext;
    public TenantController(ITenantConfigurationContext tenantContext)
    {
        this.tenantContext = tenantContext;

    }
    public List<TenantConfiguration> Get()
    {
        var tenants = (from t in tenantContext.TenantConfigurations
                       select t)
                       .ToList();

        return tenants;
    }
}

最后,在Ninject中注册ITenantConfigurationContext:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ITenantConfigurationContext>().To<TenantConfigurationContext>();
} 

注意:

您可能还需要从NuGet安装Ninject.Web.WebApi-RC软件包。