how to detect namespace when creating a class through a custom template in dotnet cli

707 views Asked by At

I'm making a custom class dotnet new template and below is my template.json. This works but I can't figure out how to detect current namespace and replace it.

template.json:

{
    "$schema": "http://json.schemastore.org/template",
    "author": "name",
    "classifications": [ "core", "console", "class" ],
    "tags": {
      "language": "C#",
      "type": "item"
    },
    "identity": "Template.ClassTemplate",
    "name": "Editable Class Template",
    "shortName": "class",
    "sourceName": "Class1"
}

C# template code file name is Class1.cs:

using System;

namespace newClass{

    public class Class1{
        
    }
}

command line to make new class: dotnet new class -n class_name

resulting c# file below and is named class_name.cs:

using System;

namespace newClass{

    public class class_name{
        
    }
}

I would like to know how to detect the namespace so I can have the option to change it or have the namespace either detected and set automatically. Thanks!

2

There are 2 answers

1
Jasen On

You can specify on the command line with your own parameter.

I got this from the samples repo https://github.com/dotnet/dotnet-template-samples/tree/master/02-add-parameters

{
    "$schema": "http://json.schemastore.org/template",
    "author": "name",
    "classifications": [ "core", "console", "class" ],
    "tags": {
      "language": "C#",
      "type": "item"
    },
    "identity": "Template.ClassTemplate",
    "name": "Editable Class Template",
    "shortName": "class",
    "sourceName": "Class1",

    
    "symbols": {
      "namespace": {
          "type": "parameter",
          "defaultValue": "MyNamespace",
          "replaces": "MY_NAMESPACE"
      }
    }
}

And it will replace the value in your source

using System;

namespace MY_NAMESPACE
{    
    public class Class1
    {            
    }
}

Usage:

dotnet new class -n class_name --namespace Foo
0
Bnaya On

Take a look at sourceName Take a look at the sourceName setting. In your case, you would set it to Class1. The value you set for sourceName will be replaced by the --name option when running the CLI, including file names or even partial file names.

For example, if you replace "sourceName": "Class1" with "sourceName": "Skeleton" and replace the content to:

using System;

namespace Skeleton
{    
    public class Class1
    {            
    }
}

With this configuration, when running the command:

dotnet new class -n Cool.Demo

You will end up with:

using System;

namespace Cool.Demo
{    
    public class Class1
    {            
    }
}

And the file names like:

  • Skeleton.cs
  • SkeletonEntity.cs

Will changed to:

  • Cool.Demo.cs
  • Cool.DemoEntity.cs