Do the new classes that implement IAsyncCommand automatically get properites injected, or does it only work via Primary Constructors?
does this work:
public class CustomerCommand() : IAsyncCommand<Customer>, IHasResult<CustomerResult>
{
public AppSettings AppSettings { get; set; } // injected?
public CustomerResult Result { get; set; } = new();
public async Task ExecuteAsync(Customer req)
{ .... }
}
// called like this:
var cmd = new CustomerCommand();
await cmd.ExecuteAsync(dto);
var res = cmd.Result;
or do I have to do this:
public class CustomerCommand(AppSettings AppSettings) : IAsyncCommand<Customer>, IHasResult<CustomerResult>
{
public CustomerResult Result { get; set; } = new();
public async Task ExecuteAsync(Customer req)
{ .... }
}
// called like this:
var cmd = new CustomerCommand(AppSettings);
await cmd.ExecuteAsync(dto);
var res = cmd.Result;
No class has any DI behavior when just creating and executing an instance:
var cmd = new CustomerCommand();
await cmd.ExecuteAsync(dto);
Injection only happens when using an IOC, either directly resolving from the IOC from an IServiceProvider:
IServiceProvider services = ...;
var command = services.GetRequiredService<CustomerCommand>();
Or by your Services/Controllers/pages etc defining a dependency that gets injected:
class MyServices(CustomerCommand customerCommand) : Service
{
//...
}
Only constructor injection is supported since that’s all that ASP .NET Core IOC supports, so you would need to define all dependencies your command needs in its constructor:
public class CustomerCommand(AppSettings AppSettings)
: IAsyncCommand<Customer,CustomerResult>
{
public CustomerResult Result { get; private set; } = new();
public async Task ExecuteAsync(Customer req) {
//....
}
}
You can execute commands directly but to get the observability in the Commands Admin UI it needs to be executed with the ICommandsExecutor, e.g:
class MyServices(ICommandExecutor executor) : Service
{
public async Task<object> Any(Customer request)
{
var command = executor.Command<CustomerCommand>();
var result = await executor.ExecuteWithResultAsync(command, request);
}
}