我有一个在ASP.NET CORE中的项目。我想在ExchangeService类的RejectExchange方法完成之前调用一个方法(未来可能是几个方法)。所以我了解了关于EventHandlers的内容,但我不知道应该将方法分配给委托的确切位置。我有ExchangeService类:
public class ExchangeService : IExchange
{
private readonly SocialNetworkContext _context;
private readonly IUser _userService;
private readonly IItem _itemService;
private readonly IExchangeRequestNotification _exchangeRequestNotificationService;
public event EventHandler<Exchange> ExchangeRejecting;
protected virtual void OnExchangeRejecting(Exchange exchange)
{
ExchangeRejecting?.Invoke(this, exchange);
}
public void RejectExchange(int id)
{
var exchange = GetById(id);
OnExchangeRejecting(exchange);
Delete(exchange);
}
public ExchangeService(SocialNetworkContext context, IUser userService, IItem itemService, IExchangeRequestNotification exchangeRequestNotificationService)
{
_context = context;
_userService = userService;
_itemService = itemService;
_exchangeRequestNotificationService = exchangeRequestNotificationService;
}
}
我希望在ExchangeRequestNorificationService中创建一个名为OnExchangeRejecting的方法,用于在交换被删除之前删除有关交换的通知。
public class ExchangeRequestNotificationService : IExchangeRequestNotification
{
private readonly SocialNetworkContext _context;
private readonly IUser _userService;
public ExchangeRequestNotificationService(SocialNetworkContext context, IUser userService)
{
_context = context;
_userService = userService;
}
public void OnExchangeRejecting(object source, Exchange exchange) => Delete(GetByExchangeId(exchange.Id));
public void Delete(ExchangeRequestNotification exchangeRequestNotification)
{
_context.Remove(exchangeRequestNotification);
_context.SaveChanges();
}
}
一切都很好,但我不明白我在哪里应该为委托分配方法。我有一个ExchangeController,在其中使用依赖注入,并将IExchangeService传递到构造函数中,然后在那里将方法分配给委托:
public ExchangeController(IExchange exchangeService, IExchangeRequestNotification exchangeRequestNotification, IChat chatService)
{
_exchangeService = exchangeService;
_exchangeRequestNotificationService = exchangeRequestNotification;
exchangeService.ExchangeRejecting += _exchangeRequestNotificationService.OnExchangeRejecting;
exchangeService.ExchangeRejecting += chatService.OnExchangeRejecting;
}
但我认为这不正确,因为在这个控制器中,我并不需要 ExchangeRequestNotificationService 和 ChatService(其还有一个名为 OnExchangeRejecting 的方法),我只需要 ExchangeService。ExchangeRequestNotificationService 仅被传递到控制器中以将方法分配给 OnRejectingExchange 方法的委托上,在未来会变得更糟(注入更多不必要的服务)。
我的问题是在哪里应该确切地将方法分配给委托?对不起,我的英语不好,我希望你能理解我的问题 :)