Skip to content

Commit 682bd65

Browse files
committed
CommandHandler lifetime missmatch
1 parent fde3ed0 commit 682bd65

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

src/MicroPlumberd.SourceGenerators/CommandHandlerSourceGenerator.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,23 @@ private static void GenerateCommandHandlerCode(SourceProductionContext context,
205205
// Generate RegisterHandlers method
206206
sb.AppendLine(" static IServiceCollection IServiceTypeRegister.RegisterHandlers(IServiceCollection services, bool scoped=true)");
207207
sb.AppendLine(" {");
208+
sb.AppendLine(" if(scoped)");
209+
sb.AppendLine(" {");
208210
foreach (var cmdType in commandTypes)
209211
{
210-
sb.AppendLine($" if(scoped) services.AddScoped<ICommandHandler<{cmdType}>, {info.ClassName}>();");
211-
sb.AppendLine($" else services.AddSingleton<ICommandHandler<{cmdType}>, {info.ClassName}>();");
212-
sb.AppendLine($" services.Decorate<ICommandHandler<{cmdType}>, CommandHandlerAttributeValidator<{cmdType}>>();");
212+
sb.AppendLine($" services.AddScoped<ICommandHandler<{cmdType}>, {info.ClassName}>();");
213+
sb.AppendLine($" services.Decorate<ICommandHandler<{cmdType}>, CommandHandlerAttributeValidator<{cmdType}>>();");
213214
}
215+
sb.AppendLine(" }");
216+
sb.AppendLine(" else");
217+
sb.AppendLine(" {");
218+
sb.AppendLine($" services.AddSingleton<{info.ClassName}>();");
219+
foreach (var cmdType in commandTypes)
220+
{
221+
sb.AppendLine($" services.AddSingleton<ICommandHandler<{cmdType}>>(sp => sp.GetRequiredService<{info.ClassName}>());");
222+
sb.AppendLine($" services.Decorate<ICommandHandler<{cmdType}>, CommandHandlerAttributeValidator<{cmdType}>>();");
223+
}
224+
sb.AppendLine(" }");
214225
sb.AppendLine(" return services;");
215226
sb.AppendLine(" }");
216227
sb.AppendLine();

0 commit comments

Comments
 (0)