我正在使用反射来查找给定类型的构造函数。然后,我想缓存它的类型上的构造函数,以便在下一次需要构造函数时即时使用它。下面的代码是这样做的,但它需要我将构造函数存储为返回对象,然后将其转换为所需的类型。我希望有一种方法可以使它更安全。通用字典上的类型约束
private static readonly ConcurrentDictionary<Type, Func<Guid, object>> AggregateConstructors = new ConcurrentDictionary<Type, Func<Guid, object>>();
public TAggregate GetAggregate<TAggregate>(Guid aggregateId) where TAggregate : AggregateRoot
{
var constructor = AggregateConstructors.GetOrAdd(typeof(TAggregate), GetConstructorFunc<TAggregate>());
// Requires a cast.
var aggregate = (TAggregate)constructor(aggregateId);
var history = eventStore.GetDomainEvents(aggregateId);
aggregate.LoadFromHistory(history);
return aggregate;
}
private Func<Guid, TAggregate> GetConstructorFunc<TAggregate>()
{
var parameter = Expression.Parameter(typeof(Guid), "aggregateId");
var constructor = typeof(TAggregate).GetConstructor(new[] { typeof(Guid) });
var lambda = Expression.Lambda<Func<Guid, TAggregate>>(Expression.New(constructor, parameter), parameter);
return lambda.Compile();
}
我想有下面几行内容:
private static readonly ConcurrentDictionary<Type, Func<Guid, SameTypeAsKey>> AggregateConstructors = new ConcurrentDictionary<Type, Func<Guid, SameTypeAsKey>>();
public TAggregate GetAggregate<TAggregate>(Guid aggregateId) where TAggregate : AggregateRoot
{
var constructor = AggregateConstructors.GetOrAdd(typeof(TAggregate), GetConstructorFunc<TAggregate>());
var aggregate = constructor(aggregateId);
var history = eventStore.GetDomainEvents(aggregateId);
aggregate.LoadFromHistory(history);
return aggregate;
}
private Func<Guid, TAggregate> GetConstructorFunc<TAggregate>()
{
var parameter = Expression.Parameter(typeof(Guid), "aggregateId");
var constructor = typeof(TAggregate).GetConstructor(new[] { typeof(Guid) });
var lambda = Expression.Lambda<Func<Guid, TAggregate>>(Expression.New(constructor, parameter), parameter);
return lambda.Compile();
}