StructureMap: How to replace object at runtime

霸气de小男生 提交于 2019-12-09 18:44:05

问题


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

Error:

System.NullReferenceException: Object reference not set to an instance of an object. at StructureMap.Pipeline.HttpContextLifecycle.findHttpDictionary() in c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs: line 50 at StructureMap.Pipeline.HttpContextLifecycle.FindCache() in c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs: line 28 at StructureMap.Pipeline.HttpContextLifecycle.EjectAll() in c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpContextLifecycle.cs: line 23 at StructureMap.Pipeline.HttpLifecycleBase`2.EjectAll() in c:\dev\opensource\structuremap\Source\StructureMap\Pipeline\HttpLifecycleBase.cs: line 18 at StructureMap.InstanceFactory.EjectAllInstances() in c:\dev\opensource\structuremap\Source\StructureMap\InstanceFactory.cs: line 127 at StructureMap.PipelineGraph.EjectAllInstancesOf() in c:\dev\opensource\structuremap\Source\StructureMap\PipelineGraph.cs: line 193 at StructureMap.Container.EjectAllInstancesOf() in c:\dev\opensource\structuremap\Source\StructureMap\Container.cs: line 393 at StructureMap.ObjectFactory.EjectAllInstancesOf() in c:\dev\opensource\structuremap\Source\StructureMap\ObjectFactory.cs: line 277


回答1:


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.

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




回答2:


Get rid of the calls to EjectAllInstancesOf(). Calling Inject() should do what you want.



来源:https://stackoverflow.com/questions/3142813/structuremap-how-to-replace-object-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!