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

时间:2009-09-22 12:00:01

标签: c# dsl dsl-tools visual-studio-2010-beta-1

信息: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 个答案:

答案 0 :(得分:2)

看起来您正在构造函数中初始化一些域类属性。最好通过创建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 Tools。 YMMV。

答案 1 :(得分:0)

虽然不是正确的方法(Paul Lalonde的答案是最好的), 以下是您在任何给定时间可能知道模型是否被序列化(=加载):

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