Is there a good way to use events with Unity?

后端 未结 2 410
悲&欢浪女
悲&欢浪女 2021-01-13 00:03
programAction = UnityContainer.Resolve();
(programAction as LoaderDriver).LoadComplete +=
    new EventHandler(Program_LoadComplete);


        
相关标签:
2条回答
  • 2021-01-13 00:33

    Yes there is a way. You would have to write an extension that adds a custom BuilderStrategy to the PostInitialization stage of the Unity BuildPipeline.

    The code for extension and strategy should look similar to this:

    public class SubscriptionExtension : UnityContainerExtension
    {
      protected override void Initialize()
      {
        var strategy = new SubscriptionStrategy();
        Context.Strategies.Add(strategy, UnityBuildStage.PostInitialization);
      }
    }
    public class SubscriptionStrategy : BuilderStrategy
    {
      public override void PostBuildUp(IBuilderContext context)
      {
        if (context.Existing != null)
        {
          LoaderDriver ld = context.Existing as LoaderDriver;
          if(ld != null)
          {
            ld.LoadComplete += Program_LoadComplete;
          }
        }
      }
    }
    

    Then you add the extension to the container

    container.AddNewExtension<SubscriptionExtension>();
    

    And when you resolve your LoaderDriver instance it will automatically subscribe to the EventHandler.

    You can find a working sample that subscribes classes to an EventAggregator in the TecX project. The source code is located in the TecX.Event.Unity project.

    0 讨论(0)
  • 2021-01-13 00:35

    I wrote a Unity Event Broker that you might find useful. See this post.

    0 讨论(0)
提交回复
热议问题