有没有一个很好的方法来使用Unity的事件? [英] Is there a good way to use events with Unity?

查看:124
本文介绍了有没有一个很好的方法来使用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.

推荐答案

是的,有一种方法。您将必须编写一个扩展,将自定义BuilderStrategy添加到Unity BuildPipeline的PostInitialization阶段。

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.

扩展和策略的代码应类似于以下内容: p>

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>();

当您解析LoaderDriver实例时,它将自动订阅EventHandler。

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

您可以在 TecX 项目中找到一个将类订阅到EventAggregator的工作示例。源代码位于TecX.Event.Unity 项目中。

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.

这篇关于有没有一个很好的方法来使用Unity的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆