开发者

StructureMap: How to replace object at runtime

开发者 https://www.devze.com 2023-01-05 07:33 出处:网络
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

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: l开发者_运维知识库ine 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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号