2

Web API アプリで Ninject を使用する必要があります (空の Web API テンプレートを使用して作成しました)。

次のナゲットパッケージをインストールしました:

Ninject.Web.WebApi

Ninject.MVC3

これが私のapplication_start

protected void Application_Start()
    {

        AreaRegistration.RegisterAllAreas();

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


    }

じぶんのNinject.Web.Common

[assembly: WebActivator.PreApplicationStartMethod(typeof(rb.rpg.backend.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(rb.rpg.backend.App_Start.NinjectWebCommon), "Stop")]

namespace rb.rpg.backend.App_Start
{
    using System;
    using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using Raven.Client;
using RemiDDD.Framework.Cqrs;    
using System.Web.Http.Dependencies;
using System.Web.Http;
using System.Collections.Generic;
using Ninject.Web.WebApi;

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>();

        RegisterServices(kernel);
        //System.Web.Mvc.DependencyResolver.SetResolver(new LocalNinjectDependencyResolver(kernel));
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(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<IDocumentSession>()
          .ToMethod(ctx => WebApiApplication.DocumentStore.OpenSession())
          .InRequestScope();
        kernel.Bind<MessageProcessor>()
            .ToMethod(ctx =>
            {
                var MessageProcessor = new MessageProcessor(kernel);

                /*...*/
                return MessageProcessor;
            })
            .InSingletonScope();
    }
}
}

アプリを再構築すると、最初の読み込みは問題なく、コントローラーがIDocumentSession. しかし、同じページをリロードすると、エラーが発生しました

「型 .. にはデフォルトのコンストラクターがありません」

4

1 に答える 1

1

Web API プロジェクトでの設定方法は次のとおりです。

nuget.org から通常の Ninject をダウンロードします。

PM> Install-Package Ninject

Web API プロジェクトで、Infrastructure という名前の新しいフォルダーをそのフォルダーに追加し、2 つのファイルを作成します。

NInjectDependencyScope.csの内容:

public class NInjectDependencyScope : IDependencyScope
{
    private IResolutionRoot _resolutionRoot;

    public NInjectDependencyScope(IResolutionRoot resolutionRoot)
    {
        _resolutionRoot = resolutionRoot;
    }

    public void Dispose()
    {
        var disposable = _resolutionRoot as IDisposable;

        if (disposable != null)
            disposable.Dispose();

        _resolutionRoot = null;
    }

    public object GetService(Type serviceType)
    {
        return GetServices(serviceType).FirstOrDefault();
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        var request = _resolutionRoot.CreateRequest(serviceType, null, new IParameter[0], true, true);

        return _resolutionRoot.Resolve(request);
    }
}

およびコンテンツを含むNInjectDependencyResolver.cs :

public class NInjectDependencyResolver : NInjectDependencyScope, IDependencyResolver
{
    private IKernel _kernel;

    public NInjectDependencyResolver(IKernel kernel) : base(kernel)
    {
        _kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NInjectDependencyScope(_kernel.BeginBlock());
    }
}

Application_Start() メソッドのGlobal.asaxファイルに次を追加します。

//Ninject dependency injection configuration
        var kernel = new StandardKernel();
        kernel.Bind<IXyzRepository>().To<EFXyzRepository>();

        GlobalConfiguration.Configuration.DependencyResolver = new NInjectDependencyResolver(kernel);

最終的なGlobal.asaxファイルは次のようになります。

public class XyzApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        //Ninject dependency injection configuration
        var kernel = new StandardKernel();
        //Your dependency bindings
        kernel.Bind<IXyzRepository>().To<EFXyzRepository>();            

        GlobalConfiguration.Configuration.DependencyResolver = new NInjectDependencyResolver(kernel);
    }
}

それはそれです!

使用例は次のとおりです。

public class PersonController : ApiController
{
    private readonly IXyzRepository repository;

    public PersonController(IXyzRepository repo)
    {
        repository = repo;

    }
...
...
...

これが役立つことを願っています。

于 2014-04-22T05:15:04.767 に答える