代码之家  ›  专栏  ›  技术社区  ›  Phill Duffy

DSL自定义构造函数-仅在创建时调用,而不加载

  •  0
  • Phill Duffy  · 技术社区  · 17 年前

    信息:VS2010,DSL工具包,C#

    我在一个域类上有一个自定义构造函数,它添加了一些子元素。我有一个问题,因为我只希望在创建域类元素时运行它,而不是每次打开图表时(它调用构造函数)。

            public Entity(Partition partition, params PropertyAssignment[] propertyAssignments)
            : base(partition, propertyAssignments)
        {
            if (SOMETHING_TO_STOP_IT_RUNNING_EACH_TIME)
            {
                using (Transaction tx = Store.TransactionManager.BeginTransaction("Add Property"))
                {
                    Property property = new Property(partition);
                    property.Name = "Class";
                    property.Type = "System.String";
                    this.Properties.Add(property);
                    this.Version = "1.0.0.0"; // TODO: Implement Correctly
                    tx.Commit();
                }
            }
        }
    
    2 回复  |  直到 17 年前
        1
  •  2
  •   Paul Lalonde    17 年前

    看起来您正在从构造函数中初始化一些域类属性。这最好通过创建addrule来完成。AddRules是在将其附加到的域类的实例添加到模型中时调用的。例如:

    [RuleOn(typeof(Entity), FireTime = TimeToFire.TopLevelCommit)]
    internal sealed partial class EntityAddRule : AddRule
    {
      public override void ElementAdded(ElementAddedEventArgs e)
      {
        if (e.ModelElement.Store.InUndoRedoOrRollback)
          return;
    
        if (e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing)
          return;
    
        var entity = e.ModelElement as Entity;
    
        if (entity == null)
          return;
    
        // InitializeProperties contains the code that used to be in the constructor
        entity.InitializeProperties();
      }
    }
    

    然后需要通过重写域模型类中的函数来注册addrule:

    public partial class XXXDomainModel
    {
      protected override Type[] GetCustomDomainModelTypes()
      {
        return new Type[] {
          typeof(EntityAddRule),
        }
      }
    }
    

    有关规则的更多信息,请参阅VS SDK文档中的“如何:创建自定义规则”主题。

    注:该解决方案基于vs 2008 DSL工具。YMMV。

        2
  •  0
  •   Luis Filipe    17 年前

    虽然不是正确的方法(保罗拉隆德的回答是最好的)。 以下是您在任何给定时间了解模型是否正在序列化(=加载)的方法:

    this.Store.TransactionManager.CurrentTransaction!= null &&
    this.Store.TransactionManager.CurrentTransaction.IsSerializing