Skip to main content

Events

For many tasks, you may need to execute custom code at the start or end of generation. For this purpose, the IGenerationEvents interface is provided. Let's look at an example:

public class TestFramework : IFrameworkTemplatePlugin, IGenerationEvents
{
public Task OnGenerationStarted(IDirectoryInfo entityDirectory, IScaffolderEntity? entity) => Task.CompletedTask;
public Task OnGenerationEnded(IDirectoryInfo entityDirectory, IScaffolderEntity? entity) => Task.CompletedTask;
}

By adding the IGenerationEvents interface to our plugin, we were able to implement two methods:

  1. OnGenerationStarted - Called before the start of generating plugin files.
  2. OnGenerationEnded - Called at the end of generating plugin files.

These functions are Tasks, so they can be asynchronous. They also take two parameters:

  1. IDirectoryInfo - DirectoryInfo containing information about the entity generation folder.
  2. IScaffolderEntity - A class representing our entity in Scaffolder (ScaffolderService, ScaffolderDashboard, ScaffolderGlobalWorker).

Thus, the Framework plugin aspnet-ddd automatically creates .NET solutions and attaches projects:

public async Task OnGenerationEnded(IDirectoryInfo serviceDirectory, IScaffolderEntity? entity)
{
string[] projectsPath =
{
"API/API.csproj",
"Application/Application.csproj",
"Domain/Domain.csproj",
"Infrastructure/Infrastructure.csproj",
"SharedKernel/SharedKernel.csproj"
};

await Cli.Wrap("dotnet")
.WithArguments(args => args
.Add("new")
.Add("sln")
.Add("--name")
.Add(serviceDirectory.Name))
.WithWorkingDirectory(serviceDirectory.FullName)
.ExecuteAsync();

foreach (string projectPath in projectsPath)
await Cli.Wrap("dotnet")
.WithArguments(args => args
.Add("sln")
.Add($"{serviceDirectory.Name}.sln")
.Add("add")
.Add(projectPath))
.WithWorkingDirectory(serviceDirectory.FullName)
.ExecuteAsync();
}

Thoughtful use of these interfaces allows for even further automation, reducing the need for manual intervention in the generated project.