Singleton Scope绑定不按预期工作

时间:2012-10-08 15:08:34

标签: c# ninject asp.net-web-api

我在我的web api应用程序中使用ninject mvc3插件。我的绑定看起来像:

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

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

我唯一的猜测是,每个请求都会以某种方式创建新内核,但事实并非如此,因为设置全局依赖项解析程序的CreateKernel方法只会在应用寿命。

我正在使用从this post获取的一些代码来使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 个答案:

答案 0 :(得分:5)

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

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

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

这似乎有效,但我对此并不满意。

答案 1 :(得分:4)

如前所述,它确实看起来像一个bug 一种选择是自己简单地实现单例扩展方法:

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


答案 2 :(得分:3)

肯定是迟到了这个帖子,但它刚好发生在一个Windows服务托管OWIN for Web API控制器并解决与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;
    }
...

希望这有帮助

答案 3 :(得分:1)

注意:我用nuget来安装ninject&amp; 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...
    }        
}
}