Visual Studio项目模板:替换为项目名称

我正在尝试在Visual Studio 2013中为EF Code-First上下文类创建项模板。 除了我想要一个指向当前项目中的命名空间的using语句之外,我已经完成了所有工作。 例如,在ProjectName .Contexts中创建模板项的实例时,using语句将为:

使用ProjectName .Models

问题是我找不到替换项目模板中的部分的方法。 尽管我可以确定,$ projectname $和$ safeprojectname $仅适用于项目模板,而不适用于项目模板。

我的模板如下:

using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using $safeprojectname$.DAL.Models; // This is the problem line namespace $rootnamespace$ { public class $safeitemrootname$ : DbContext { // Constructors ======================================================= public $safeitemrootname$() : base("$safeitemrootname$") { } // DBSets ============================================================= // public DbSet Companies { get; set; } // Configuration ====================================================== protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove(); } } } 

更新:

回应Hans的评论,这是我尝试使用$ projectname $时的输出($ safeprojectname $做同样的事情):

 using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using $projectname$.DAL.Models; // This is the problem line 

如您所见,$ projectname $替换只是被忽略了。

任何帮助,将不胜感激,

贾森

如下面的MSDN链接所述:

https://msdn.microsoft.com/en-us/library/eehb4faa.aspx

只有在“新建项目”对话框中提到项目名称时,项目名称才会出现。 因此,如果您在现有项目中使用它,它将无法工作。 见下面的截图:

安全项目名称

我的同事在工作中找到了一个修复它的参数来检测当前的项目名称。

 $rootnamespace$ 

Root.vstemplate添加copyParameters="true" ,如下所示

  ProjectTemplateLink ProjectName="Domain.$projectname$" CopyParameters="true"> 

在代码中使用$ext_projectname$来解析项目名称

 using Provider.$ext_projectname$ 

我找到了一种解决方法 – 使用自定义模板向导,并在源代码管理资源管理器中检索当前选定的项目。

由于CUSTOM项目模板仅在解决方案树中选择项目节点时才在“添加新”菜单中可用,因此可以确定项目名称(以及EnvDTE可用的所有其他信息)并将其添加到replacementmentsDictionary中。

 using EnvDTE80; public void RunStarted(object automationObject, Dictionary replacementsDictionary, WizardRunKind runKind, object[] customParams) { //Adding by template is unavailable in the context menu when selecting more than one item -> use index 0. UIHierarchyItem selectedUiHierarchyItem = (UIHierarchyItem )dte.ToolWindows.SolutionExplorer.SelectedItems[0]; //not null when selecting solution node (when adding a project) Solution selectedSolution = selectedUiHierarchyItem.Object as Solution //not null when selecting project node (when adding an item) or when selecting a solution folder (when adding a project) Project selectedProject = selectedUiHierarchyItem.Object as Project; //Determine which kind of project node: if (selectedProject != null) { if (selectedProject.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) { //solution folder } else { //project replacementsDictionary.Add("$projectname$", selectedProject.Name); } } }