【问题标题】:C# custom project templateC# 自定义项目模板
【发布时间】:2013-06-02 17:29:30
【问题描述】:

我正在为 C# 创建自己的项目模板,其中包含更多项目。

我在其中添加了我自己的向导。效果很好。

但是,当我尝试将一些项目自定义参数放入替换字典中时,在我的向导库中,我在我的项目中获得了原始值(未替换)(保持为“$connectionString$”)。

例如,如果我在 RunStarted 方法中添加这段代码:

private string _connectionString = "Lorem ipsum for example";
public void RunStarted(object automationObject, Dictionary<string, string>replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
    replacementsDictionary.Add("$connectionString$", _connectionString);
}

在我的 web.config 中:

<connectionStrings>
    <add name="DAL.Database.Properties.Settings.MyConnectionString" connectionString="$connectionString$" providerName="System.Data.SqlClient" />
</connectionStrings>  

甚至在我的 .vstemplate 文件中,我也看到该文件被标记为检查和修改参数:

<ProjectItem ReplaceParameters="true" OpenInEditor="true" TargetFileName="Web.config">Web.config</ProjectItem>

注意:只有当我将硬编码值放入 .vstemplate 文件中时,它才有效,例如:

<CustomParameters>
    <CustomParameter Name="$connectionString$" Value="Some dummy value" />
</CustomParameters>

但这不是我想要的。 现在我想知道,可能是什么问题?

【问题讨论】:

    标签: c# visual-studio-2010 visual-studio templates visual-studio-2012


    【解决方案1】:

    我终于找到了解决这个问题的办法。

    要从实现 IWizard 接口的类库中传递自定义参数,您必须创建自己的字典,并在其中放置自定义数据。

    然后将数据从那里复制到 replacementsDictionary 字典。

    这是如何在多个项目模板之间共享包含要替换的值的同一个字典的示例:

    private static Dictionary<string, string> _sharedDictionary = new Dictionary<string, string>();
    
    public void RunStarted(object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind, object[] customParams)
        {
            if (runKind == WizardRunKind.AsMultiProject)
            {
                try
                {                    
                    _sharedDictionary.Add("$connectionString$", connectionString);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            if (_sharedDictionary != null)
            {
                foreach (KeyValuePair<string, string> dictItem in _sharedDictionary)
                {
                    if (!replacementsDictionary.ContainsKey(dictItem.Key))
                    {
                        replacementsDictionary.Add(dictItem.Key, dictItem.Value);
                    }
                }
            }
        }
    

    因为 _sharedDictionary 被标记为静态所有实例将共享同一个字典,并且需要替换的值将在您的所有项目模板中可用。

    另外,不要忘记在所有链接项目中包含 .vstemplate 文件 WizardExtension 部分。

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 2013-06-19
      • 2018-12-15
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多