首页 > 解决方案 > Clock.Now 在域级别 abp.io 中不可用

问题描述

从 aspnet.boilerplate 移动到 abp.io 我发现Clock不再是一个静态对象。这是一项服务(IClock)。

我的问题是:如何使用 DDD 模型在域级别使用其功能?例如:我有一个描述事件的类(受此 abp.io文章的启发):

    public class Event : FullAuditedAggregateRoot<Guid> {

        public string Title { get; set; }

        public string Description { get; set; }

        public bool IsFree { get; set; }

        public DateTime StartTime { get; set; }

        public DateTime BookingTime { get; set; }

        public ICollection<EventAttendee> Attendees { get; set; }

        public void AddAttendee(Guid attendeeId) {
            if (Clock.Now < BookingTime) {    <== here!
                throw new BusinessException(
                    "Error.EventClosed",
                    $"You cannot book this event before {BookingTime}.");
            }

            // ...

            var attendee = new EventAttendee { UserId = attendeeId };
            _attendees.Add(attendee);
        }

        public Event() {
            Attendees = new List<EventAttendee>();
        }
    }

在这里,我想使用 Clock.Now(在 aspnet.boilerplate 中作为静态对象提供),但在 abp.io 中不使用,它仅作为服务提供。

标签: abp

解决方案


我也经常需要这个。我IClock通过以下示例中的参数来解决,因此我可以充分利用IClock.

 public void AddAttendee(Guid attendeeId, IClock clock)
 {
        if (clock.Now < BookingTime) {   
            throw new BusinessException(
                "Error.EventClosed",
                $"You cannot book this event before {BookingTime}.");
        }

        // ...

        var attendee = new EventAttendee { UserId = attendeeId };
        _attendees.Add(attendee);
 }

然后我将它作为我调用它的参数传递。


我认为可扩展性可能是它不像 aspnetboilerplate 那样静态的主要原因。

这个用法对我来说很有意义,我希望它对你有用。


参考:

  1. https://volosoft.com/blog/Prefer-Singleton-Pattern-over-Static-Class
  2. https://docs.abp.io/en/abp/latest/Timing#datetime-normalization
  3. https://github.com/abpframework/abp#application-modules

推荐阅读