9

我将 ninject mvc3 插件与我的 web api 应用程序一起使用。我有一个看起来像这样的绑定:

kernel.Bind<IFoo>().To<Foo>().InSingletonScope();

我的解释是内核将恰好创建一个实例Foo并适当地重用它。通过在 的构造函数中放置断点Foo,我可以清楚地看到每个请求都会调用一次,但我无法解释原因。

我唯一的猜测是,每个请求都会以某种方式创建一个新内核,但情况似乎并非如此,因为CreateKernel设置全局依赖解析器的方法在应用程序生命周期中只运行一次。

我正在使用从这篇文章中获取的一些代码来使 ninject 与 mvc 4 配合得很好。由于框架的更改,我不得不制作一个额外的包装器,并分配给GlobalConfiguration.Configuration.DependencyResolver

public class NinjectResolver : NinjectScope, IDependencyResolver
{
    private readonly IKernel _kernel;
    public NinjectResolver(IKernel kernel)
        : base(kernel)
    {
        _kernel = kernel;
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(_kernel.BeginBlock());
    }
}

我究竟做错了什么?

4

4 回答 4

5

我永远无法让它正常工作,我不知道为什么。我的猜测是它与 MVC4 集成目前有点不成熟有关。

作为替代方案,我正在使用:

kernel.Bind<IFoo>().ToConstant(new Foo());

这似乎可行,但我对此不太满意。

于 2012-10-12T22:11:45.383 回答
4

就像前面提到的那样,它看起来确实像一个错误。
一种选择是自己简单地实现一个单例扩展方法:

public static class NinjectSingletonExtension
{
    public static CustomSingletonKernelModel<T> SingletonBind<T>(this IKernel i_KernelInstance)
    {
        return new CustomSingletonKernelModel<T>(i_KernelInstance);
    }
}

public class CustomSingletonKernelModel<T>
{
    private const string k_ConstantInjectionName = "Implementation";
    private readonly IKernel _kernel;
private static object padlock = new Object();

    private T _concreteInstance;


    public CustomSingletonKernelModel(IKernel i_KernelInstance)
    {
        this._kernel = i_KernelInstance;
    }

    public IBindingInNamedWithOrOnSyntax<T> To<TImplement>(TImplement i_Constant = null) where TImplement : class, T
    {
        _kernel.Bind<T>().To<TImplement>().Named(k_ConstantInjectionName);
        var toReturn =
            _kernel.Bind<T>().ToMethod(x =>
                                       {
                                           if (i_Constant != null)
                                           {
                                               return i_Constant;
                                           }

                                           if (_concreteInstance == null)
                       {
                       lock (padlock)
                       {
                        if (_concreteInstance == null)
                        {
                            _concreteInstance = _kernel.Get<T>(k_ConstantInjectionName);
                        }
                           }
                       }


                                           return _concreteInstance;
                                       }).When(x => true);

        return toReturn;
    }
}

然后只需使用:

i_Kernel.SingletonBind<T>().To<TImplement>();

而不是

i_Kernel.Bind<T>().To<TImplement>().InSingletonScope();


于 2014-04-03T14:18:51.917 回答
4

当然迟到了这个线程,但它只是发生在我身上,一个 Windows 服务为 Web API 控制器托管 OWIN 并使用 Ninject 解决依赖关系,InSingletonScope() 在我执行以下操作之前无法正常工作:

var kernel = new StandardKernel();
...
kernel.Bind<Foo>().ToSelf().InSingletonScope();
kernel.Bind<IFoo>().ToMethod(context => context.Kernel.Get<Foo>());
...

// Controllers ask for the dependency as usual...
public class SomeController : ApiController
{
    readonly IFoo _foo;

    public SomeController(IFoo foo)
    {
        _foo = foo;
    }
...

希望这可以帮助

于 2017-03-22T22:12:30.940 回答
1

注意:我使用 nuget 安装了 ninject 和 ninject.web.mvc(我相信你也这样做了)。

我无法看到您的其余代码,但这是我在“NinjectDependencyScope”类中的内容。(我认为您的只是称为 NinjectScope,可能与您的代码有一些其他命名不一致)

public class NinjectDependencyScope : IDependencyScope
{
    private IResolutionRoot _resolver;

    internal NinjectDependencyScope(IResolutionRoot resolver)
    {
        Contract.Assert(resolver != null);

        _resolver = resolver;
    }

    #region IDependencyScope Members

    public void Dispose()
    {
        var disposable = _resolver as IDisposable;
        if (disposable != null)
            disposable.Dispose();

        _resolver = null;
    }

    public object GetService(Type serviceType)
    {
        if (_resolver == null)
            throw new ObjectDisposedException("this", "This scope has already been disposed");
        return _resolver.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        if (_resolver == null)
            throw new ObjectDisposedException("this", "This scope has already been disposed");

        return _resolver.GetAll(serviceType);
    }

    #endregion
}

这是我的 NinjectWebCommon 类(位于 App_Start 文件夹中):

using System;
using System.Web;
using System.Web.Http;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;

[assembly: WebActivator.PreApplicationStartMethod(typeof(ABCD.Project.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(ABCD.Project.Web.App_Start.NinjectWebCommon), "Stop")]

namespace ABCD.Project.Web.App_Start
{
public static class NinjectWebCommon 
{
    private static readonly Bootstrapper Bootstrap = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        Bootstrap.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        Bootstrap.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);

        // Set Web API Resolver
        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)
    {
        //var modules = new INinjectModule[] { new NinjectBindingModule(), };
        //kernel.Load(modules);
        Here's where you would load your modules or define your bindings manually...
    }        
}
}
于 2012-10-08T15:15:01.563 回答