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 allows me to resolve my objects already connected to the event?

Alternatively, is there a preferred way to achieve the same result? I noticed that sometimes when I don’t see a “function”, because a template that I don’t know about is preferred.

+6
source share
2 answers

Yes, there is a way. You will need to write an extension that adds a custom BuilderStrategy to the PostInitialization Unity BuildPipeline step.

The code for the extension and strategy should look something like 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 enable your instance of LoaderDriver, it will automatically subscribe to the EventHandler.

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

+4
source

I wrote a Unity Event Broker that might come in handy. See this post .

0
source

Source: https://habr.com/ru/post/903949/


All Articles