事务脚本实现

时间:2016-12-10 15:29:22

标签: c# design-patterns transactions dto

请您告诉我,这两种(如果有的话)交易脚本模式中的哪一种方法是正确的?

基本上我需要实现“纯”TS,这不是以某种方便的方式弯曲它。问题是,当我从Table Data Gateway获取数据时,我是否应该存储它们,针对事务的不同部分(为了清晰起见的逻辑部分),并在需要的地方使用它们,或者获取数据不存储它们但是直接使用它们如果再次需要相同的数据,请调用表网关并请求它。

示例:http://pastebin.com/hGCgrfEs

感谢。希望如果不让我知道它是有道理的:)

1 个答案:

答案 0 :(得分:0)

TSDoSomething2类更接近一个好的解决方案,我建议实现一个SOLID脚本实现:

public class OrderBusiness : IAcceptVisitOrder
{
    private readonly string _id;

    private int _status;

    public OrderBusiness(string id, int status)
    {
        _id = id;
        _status = status;
    }

    public void ChangeStatus(int newStatus)
    {
        //validation logic....
        _status = newStatus;
    }

    public void Accept(IOrderVisitor visitor)
    {
        if (visitor == null) throw new ArgumentNullException(nameof(visitor));
        visitor.Visit(_id, _status);
    }
}

public class Client
{
    private readonly OrderApplicationService _service;
    //Get from Service locator like ninject, etc
    private readonly IReader<OrderBusiness, string> _reader = new OrderBusinessReader();
    private readonly IOrderVisitor _visitor = new UpdateOrderVisitor();

    public Client()
    {
        _service = new OrderApplicationService(_reader, _visitor);
    }
    public void Run(UpdateOrderCommand command)
    {
        _service.When(command);
    }
}

public class UpdateOrderCommand
{
    [Required]
    public string Id { get; set; }
    [Required]
    public int Status { get; set; }
}

public class OrderApplicationService
{
    private readonly IReader<OrderBusiness, string> _reader;
    private readonly IOrderVisitor _visitor;

    public OrderApplicationService(IReader<OrderBusiness, string> reader, IOrderVisitor visitor)
    {
        if (reader == null) throw new ArgumentNullException(nameof(reader));
        if (visitor == null) throw new ArgumentNullException(nameof(visitor));
        _reader = reader;
        _visitor = visitor;
    }

    public void When(UpdateOrderCommand command)
    {
        var order = GetBusinessObject(command.Id);
        order.ChangeStatus(command.Status);
        order.Accept(_visitor);
    }

    private OrderBusiness GetBusinessObject(string id)
    {
        if (id == null) throw new ArgumentNullException(nameof(id));
        return _reader.Read(id);
    }
}

public interface IReader<out T, in TK>
{
    T Read(TK id);
}

public interface IAcceptVisitOrder
{
    void Accept(IOrderVisitor visitor);
}

public interface IOrderVisitor
{
    void Visit(string id, int status);
}

public class OrderBusinessReader : IReader<OrderBusiness, string>
{
    public OrderBusiness Read(string id)
    {
        //Read data from db with EF, ADO.NET, ETC
        var status = 0;
        return new OrderBusiness(id, status); 
    }
}

class UpdateOrderVisitor : IOrderVisitor
{
    public void Visit(string id, int status)
    {
        //Persist to database, etc
    }
}

希望这有帮助!
问候!