StructureMap: How to replace object at runtime

2019-04-12 13:13发布

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

2条回答
做个烂人
2楼-- · 2019-04-12 13:44

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.

查看更多
趁早两清
3楼-- · 2019-04-12 13:53

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

查看更多
登录 后发表回答