【问题标题】:Ninject InSingletonScope with Web Api RCNinject InSingletonScope 与 Web Api RC
【发布时间】:2012-07-06 14:20:14
【问题描述】:

我在使用 Ninject 的 InSingletonScope 与 Web Api RC 绑定时遇到了一些困难。无论我如何创建绑定,看起来 Web Api 正在处理范围/生命周期而不是 Ninject。

我尝试了一些关于连接 Ninject 的变体。最常见的与此处的答案相同: ASP.NET Web API binding with ninject

我也试过这个版本: http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/

在这两者中,我实际上是在创建一个开箱即用的 Web Api 项目,然后按照任一帖子中的描述添加 Ninject 包。最后,我添加了 Resolver 和 Scope 类,例如 StackOverflow 版本:

public class NinjectDependencyScope : IDependencyScope
{
    private IResolutionRoot resolver;

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

        this.resolver = resolver;
    }

    public void Dispose()
    {
        IDisposable 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);
    }
}

和:

 public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
    private IKernel kernel;

    public NinjectDependencyResolver(IKernel kernel)
        : base(kernel)
    {
        this.kernel = kernel;
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(kernel.BeginBlock());
    }
}

然后,NinjectWebCommon 看起来像这样:

using System.Web.Http;
using MvcApplication2.Controllers;

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

namespace MvcApplication2.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>();

            // Register Dependencies
            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)
        {
            kernel.Bind<ILogger>().To<Logger>().InSingletonScope();
        }
    }
}

ILogger 和 Logger 对象不做任何事情,但可以说明问题。 Logger 执行 Debug.Writeline 以便我可以看到它何时被实例化。页面的每次刷新都表明每次调用都会刷新它,而不是我希望的单例。这是一个使用 Logger 的控制器:

public class ValuesController : ApiController
{
    private readonly ILogger _logger;
    public ValuesController(ILogger logger)
    {
        _logger = logger;
        _logger.Log("Logger created at " + System.DateTime.Now.ToLongTimeString());
    }
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
    // POST api/values
    public void Post(string value)
    {
    }
    // PUT api/values/5
    public void Put(int id, string value)
    {
    }
    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

当我把trace信息放到内核的创建中时,似乎表明内核只创建了一次。所以……我没看到什么?为什么单例不持久化?

【问题讨论】:

    标签: asp.net-web-api ninject


    【解决方案1】:

    使用

    public IDependencyScope BeginScope()
    {
        return new NinjectDependencyScope(kernel);
    }
    

    并且不要在NinjectDependencyScope中处理内核

    【讨论】:

    • 雷莫,非常感谢您的解决方案!我也在努力解决 web api 中的单例问题。但是,我认为我不理解您的解决方案。能详细点吗?
    • Ninject 本身知道请求持续时间,因此无需创建新范围。基本上这段代码忽略了这个 MVC4 特性。只有在 WebAPI 自托管的情况下,您才需要以不同的方式做事,但激活块不是正确的方法。
    • 我一直在寻找这个解决方案。谢谢!也许 NinjectDependencyScope 的这个实现应该在 WebApi 扩展项目中?
    • @Remo :您能否提供一些有关您的答案的详细信息,例如执行“new NinjectDependencyScope(kernel);”与“new NinjectDependencyScope(kernel.BeginBlock());”之间的区别和不在“NinjectDependencyScope”中处理内核的影响
    • @RemoGloor:您能否确认一下我在这里托管的 NinjectScope 和 NinjectResolver:github.com/abpatel/Code-Samples/blob/master/src/… 还可以保留内核而不释放它会导致内存泄漏?
    【解决方案2】:

    @Remo 格洛尔 当我在 WebAPI 的 InMemoryHost 中运行您的代码并运行集成测试时,一切正常,我确实有单例。 如果我在 VS Cassini Web 服务器中运行 WebAPI 解决方案 第一次运行成功 当我单击刷新时,我收到异常: 加载 Ninject 组件 ICache 时出错 内核的组件容器中尚未注册此类组件。

    如果我使用 BeginBlock 返回旧代码,它在 Cassini 中有效,但 IsSingleton 在集成测试中不再有效。

    【讨论】:

    • 如果对象是从已经释放的内核请求的,通常会发生此错误。但我没有任何在 Cassini 中运行 WebAPI 的经验。顺便说一句:在答案中提问是违反 SO 政策的。请将此放入新问题或在某处添加评论。
    【解决方案3】:

    您可以简单地实现自己的单例,而不是不释放内核(不会调用内部释放):

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


    注意:虽然它只对第一个请求很重要,但这个实现不是线程安全的。

    【讨论】:

    • 刷新我的页面时仍然遇到TImplement的构造函数。所以它仍然出于某种原因创建新对象。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多