Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to use events with Unity?

programAction = UnityContainer.Resolve<LoaderDriver>();
(programAction as LoaderDriver).LoadComplete +=
    new EventHandler(Program_LoadComplete);

Is there a configuration that let's me resolve my objects having already been wired to an event?

Alternately, is there a preferred way to achive the same result? I've noticed that sometimes when I don't see a "feature" its because a pattern I don't know about is preferred.

like image 593
Aaron Anodide Avatar asked Dec 16 '11 20:12

Aaron Anodide


People also ask

Are events slow Unity?

Please note that it's not that unity events are slow it's delegates are very fast. I run same test in build a while ago and unity events is roughly 11x slower than delegate but both GetComponent and changing position are 4x slower than unity events and toggling game object activate state is 6-7 slower than that.

When should I use events C#?

Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, see Calling Synchronous Methods Asynchronously.


1 Answers

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.

like image 138
Sebastian Weber Avatar answered Oct 17 '22 14:10

Sebastian Weber