-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve domain event publisher implementation
- Loading branch information
1 parent
b090ff8
commit e0b9c2e
Showing
5 changed files
with
270 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
...dehard.Infrastructure/Codehard.Infrastructure.EntityFramework/InstanceActivatorFactory.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using System.Collections.Concurrent; | ||
using System.Linq.Expressions; | ||
|
||
namespace Codehard.Infrastructure.EntityFramework; | ||
|
||
internal class InstanceActivatorFactory | ||
{ | ||
private readonly ConcurrentDictionary<Type, Func<object>> cache = new(); | ||
|
||
private static InstanceActivatorFactory? instance; | ||
|
||
public static readonly InstanceActivatorFactory Instance = instance ??= new InstanceActivatorFactory(); | ||
|
||
private InstanceActivatorFactory() | ||
{ | ||
} | ||
|
||
public object CreateInstance(Type type) | ||
{ | ||
if (this.cache.TryGetValue(type, out var activator)) | ||
{ | ||
return activator(); | ||
} | ||
|
||
var expression = Expression.Lambda<Func<object>>(Expression.New(type)); | ||
var compiledExpression = expression.Compile(); | ||
|
||
this.cache.AddOrUpdate(type, _ => compiledExpression, (_, _) => compiledExpression); | ||
|
||
return compiledExpression(); | ||
} | ||
|
||
public object CreateInstance<T>() | ||
{ | ||
return this.CreateInstance(typeof(T)); | ||
} | ||
} |
Oops, something went wrong.