Skip to content

Commit

Permalink
using Activator.CreateInstance() to build aggregates w/ no public ctor.
Browse files Browse the repository at this point in the history
Closes GH-2825
  • Loading branch information
jeremydmiller committed Nov 30, 2023
1 parent 497dde1 commit 5aae5b6
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
}
else if (defaultConstructor?.IsPublic == false)
{
writer.Write($"{Aggregate.Usage} ??= AggregateBuilder();");
writer.Write($"{Aggregate.Usage} ??= ({AggregateType.FullNameInCode()}){typeof(Activator).FullNameInCode()}.{nameof(Activator.CreateInstance)}(typeof({AggregateType.FullNameInCode()}), true);");
}
else
{
Expand Down
14 changes: 6 additions & 8 deletions src/Marten/Events/CodeGeneration/DefaultAggregateConstruction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using FastExpressionCompiler;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
Expand All @@ -13,7 +14,6 @@ internal class DefaultAggregateConstruction: SyncFrame
{
private readonly ConstructorInfo _constructor;
private readonly Type _returnType;
private readonly Setter _setter;
private Variable _event;

public DefaultAggregateConstruction(Type returnType, GeneratedType generatedType)
Expand All @@ -23,13 +23,11 @@ public DefaultAggregateConstruction(Type returnType, GeneratedType generatedType
_constructor = returnType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);



if (_constructor != null && !_constructor.IsPublic)
{
var ctor = Expression.New(_constructor);
var lambda = Expression.Lambda(ctor);
var func = lambda.Compile();
_setter = new Setter(func.GetType(), "AggregateBuilder") { InitialValue = func };
generatedType.Setters.Add(_setter);

}
}

Expand All @@ -53,9 +51,9 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
$"throw new {typeof(InvalidOperationException).FullNameInCode()}($\"There is no default constructor for {_returnType.FullNameInCode()}{AdditionalNoConstructorExceptionDetails}.\");"
);
}
else if (_setter != null)
else if (!_constructor.IsPublic)
{
writer.WriteLine("return AggregateBuilder();");
writer.WriteLine($"return ({_returnType.FullNameInCode()}){typeof(Activator).FullNameInCode()}.{nameof(Activator.CreateInstance)}(typeof({_returnType.FullNameInCode()}), true);");
}
else
{
Expand Down

0 comments on commit 5aae5b6

Please sign in to comment.