为structuremap定义自定义转换以自动注册命令、CommandHandlers

本文关键字:注册 命令 CommandHandlers structuremap 定义 自定义 转换 | 更新日期: 2023-09-27 18:05:23

我在最近的项目中使用CQRS模式,所以我定义了一些Commands,我称之为CommandParameterCommandHandlers

对于CommandParameters,我有这些Class es和Interface s:

public interface ICommandParameter
{
}
public abstract class BaseEntityCommandParameter<T> : IAggregateRoot,ICommandParameter
    where T : ModelEntitySuperType, new()
{
    public T Entity { get; set; }
    protected BaseEntityCommandParameter()
    {
        Entity = new T();
    }
}
public class InsertCommandParameter<T> : BaseEntityCommandParameter<T>
    where T : class, new()
{
}

对于CommandHandlers,我定义了ClassInterface:

public interface ICommandHandler<TCommandParameter>
    where TCommandParameter :ICommandParameter
{
    void Handle(TCommandParameter parameter);
    string CommandCode { get; }
}
public class InsertCommandHandler<TCommandParameter, TEntity> 
    : ICommandHandler<TCommandParameter>
    where TCommandParameter : BaseEntityCommandParameter<TEntity>, new()
    where TEntity : ModelEntitySuperType, IAggregateRoot, new()

,我用它们为每个Entity制作适当的CommandParameter s和CommandHandler s,例如Order,我有:

public class OrderInsertCommandParameter:InsertCommandParameter<Order>
{
}
public class OrderInsertCommandHandler 
    : InsertCommandHandler<OrderInsertCommandParameter, Order>
{
    private readonly IUnitOfWorkFactory _factory;
    public OrderInsertCommandHandler(IUnitOfWorkFactory factory,
        IRepository<Order> repository)
        : base(repository)
    {
        _factory = factory;
    }
    public override void Handle(OrderInsertCommandParameter parameter)
    {
        var uow = _factory.Create();
        parameter.Entity.OrderCreationTime = DateTime.Now;
        base.Handle(parameter);
        uow.Commit();
    }
}

我想注册这些CommandParameter s和适当的CommandHandler s使用structuremap自动,我怎么能定义一个自定义转换来做到这一点?

为structuremap定义自定义转换以自动注册命令、CommandHandlers

可以这样做:

container.Configure(r => 
{ 
    r.Scan(s => 
    { 
        s.Assembly(typeof(ICommandHandler<>).Assembly);
        s.ConnectImplementationsToTypesClosing(typeof(ICommandHandler<>)); 
    }); 
});