本文介绍了StructureMap:如何在运行时替换对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ISession (NHibernate) 的模拟实例注入到结构映射中.目前,它全部以 Bootstrap 方法连接起来,但我想用模拟方法替换注入的方法.我试过 EjectAllInstancesOf 但它抛出了 execption.

I am trying to inject mocked instance of ISession (NHibernate) to structure map. Currently it all wires it up in a Bootstrap method, but I want to replace the one that is injected with a mocked one. I tried EjectAllInstancesOf but it throw execption.

 [TestFixtureSetUp]
        public void TestFixtureSetup()
        {
            Bootstrapper.Bootstrap();
           //TODO: need to remove already wired up types that we are mocking.
            var mockSession = MockRepository.GenerateStub<ISession>();
            var mockLoggerFactory = MockRepository.GenerateStub<ILoggerFactory>();

            ObjectFactory.EjectAllInstancesOf<ISession>();
            ObjectFactory.EjectAllInstancesOf<ILoggerFactory>();

            ObjectFactory.Inject<ISession>(mockSession);
            ObjectFactory.Inject<ILoggerFactory>(mockLoggerFactory);
        }

错误:

System.NullReferenceException: 未将对象引用设置为实例的一个对象.在StructureMap.Pipeline.HttpContextLifecycle.findHttpDictionary() 中c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:在 StructureMap.Pipeline.HttpContextLifecycle.FindCache() 中的第 50 行c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:在 StructureMap.Pipeline.HttpContextLifecycle.EjectAll() 中的第 28 行c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs:在 StructureMap.Pipeline.HttpLifecycleBase`2.EjectAll() 中的第 23 行c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpLifecycleBase.cs:在 StructureMap.InstanceFactory.EjectAllInstances() 中的第 18 行c:\dev\opensource\structuremap\Source\StructureMap\InstanceFactory.cs:在 StructureMap.PipelineGraph.EjectAllInstancesOf() 中的第 127 行c:\dev\opensource\structuremap\Source\StructureMap\PipelineGraph.cs:在 StructureMap.Container.EjectAllInstancesOf() 中的第 193 行c:\dev\opensource\structuremap\Source\StructureMap\Container.cs: 行393 在 StructureMap.ObjectFactory.EjectAllInstancesOf() 中c:\dev\opensource\structuremap\Source\StructureMap\ObjectFactory.cs:第 277 行

推荐答案

您收到此异常是因为您的插件类型 (ISession) 在 StructureMap 中设置为 HttpContext 生命周期,并且单元测试中没有 HttpContext.这可能是 StructureMap 中的一个错误,它可能应该抛出它自己的异常来解释问题,而不是遇到 NullReferenceException.

You are getting this exception because your plugin type (ISession) is set up in StructureMap as a HttpContext lifecycle, and there is no HttpContext in a unit test. This is probably a bug in StructureMap, it should probably throw it's own exception explaining the problem instead of hitting a NullReferenceException.

无论如何,在您的单元测试设置 (Boostrapper) 中,将 ISession 的生命周期更改为 Hybrid 或 HttpContext 之外的其他内容.

at any rate, in your unit test setup (Boostrapper), change the lifecycle of ISession to Hybrid or something besides HttpContext.

这篇关于StructureMap:如何在运行时替换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 18:38