我正在使用反射來查找給定類型的構造函數。然後,我想緩存它的類型上的構造函數,以便在下一次需要構造函數時即時使用它。下面的代碼是這樣做的,但它需要我將構造函數存儲爲返回對象,然後將其轉換爲所需的類型。我希望有一種方法可以使它更安全。通用字典上的類型約束
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();
}