简体   繁体   中英

Why does Unity custom BuilderStrategy returns null even after setting Existing property

I'm using version 2 of Unity (that comes with Prism4). I'm trying to write an extension that can return enumerable of a non registered type. Following code is what I've written but I'm getting null after resolve call.

        class EnumerableStrategy : BuilderStrategy
        {
            public override void PreBuildUp(IBuilderContext context)
            {
                context.Existing = new []{"Test"};
                context.BuildComplete = true;
            }
        }

        class EnumerableExtension : UnityContainerExtension
        {
            protected override void Initialize()
            {
                Context.BuildPlanStrategies.AddNew<EnumerableStrategy>( Microsoft.Practices.Unity.ObjectBuilder.UnityBuildStage.PreCreation);
            }
        }
        static void Main(string[] args)
        {

            var container = new UnityContainer();
            container.AddNewExtension<EnumerableExtension>();
            var items = container.Resolve<IEnumerable<string>>();
            foreach (var item in items)
                Console.WriteLine(item.ToString());
        }

Items variable turns out to be null. Why?

Add the strategy to the Strategies collection, not the BuildPlanStrategies.

BuildPlanStrategies is for constructing the objects that will construct the resolved objects. That's not what you're doing - you're just returning the objects directly. I'm surprised you got null, actually - I would have expected an invalid cast exception in there somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM