更改参数 - 谁负责?

Changing a Parameter - who's responsible?

我有一个 table 被另一个应用程序填充。此 table 包含名为 IsMailSent 的属性。

EF 根据数据库数据构建我的 Request 类型的对象。

对象看起来像这样:

public class Request {
    int SomeInt;
    bool IsMailSent;
    SomeObject SomeObject;
}

现在我想创建一个服务,它将加载所有带有 IsMailSent == false 的条目并将此邮件发送给他们的收件人。

我当前的代码如下: 一个名为 MailMessageService 的 class 有一个 Start() 和一个 Stop() 方法。 Start 方法如下所示:

public void Start(int delay) {
        tokenSource = new CancellationTokenSource();
        T = new Task(() => {
            MailService ms = new MailService(Res.ServerAddress, int.Parse(Res.ServerPort));
            while (true) {
                var messages = GetMailMessages(_context.Requests.Where(o => !o.IsMailSent));
                ms.Send(messages);
                Thread.Sleep(delay);
            }
        }, tokenSource.Token);
    }

方法 GetMailMessages 接收 Request 的集合并构建 MailMessages 的集合。目前我创建了一个 class 继承自 MailMessage 并包含对相应请求对象的引用。背后的想法是 MailService (负责发送邮件)应该将 IsMailSent 属性 设置为 true.

So the Send() Method should set IsMailSent = true

但这是最​​好的方法吗?据我了解 SOLID 原则,MailService 不应该负责设置此 属性(因为它负责发送邮件)- 或者我错了吗?

您可以添加一种将 IsMailSent 设置为 Request class 的方法。所以 Request class 最终会决定是否将 IsMailSent 设置为 true。这样设置的代码还在Requestclass里面,还是有可能影响到设置的

例如

public class Request {
    // Property
    public bool IsMailSent { get; private set; }

    public void MailSent() {
       // TODO check some conditions
       if (...) {
           ...
       }

       // If everything is correct set the property
       IsMailSent = true;
    }
}

然后在 MailService.Send(...) 中调用 MailSent 方法。