我正在尝试为我的应用程序构建通知提供程序(警报)。目前我只需要在请求之间生成通知,但是将此功能包装在提供程序中将允许我稍后将其连接到数据库。
我有 3 种类型的通知:
public enum NotificationType
{
Success,
Error,
Info
}
和一个通知对象:
public class Notification
{
public NotificationType Type { get; set; }
public string Message { get; set; }
}
我想将所有通知放入List<Notification>
并将其加载到ViewData["Notifications"]
然后我可以使用助手来读取ViewData["Notifications"]
和渲染它:
我想实现我自己的 NotificationProvider 来维护List<Notification>
对象。
我希望提供者读取 TempData["Notifications"] 并将其加载到List<Notification> Notifications
变量中。然后我可以将通知加载到 ViewData["Notifications"] 以供我的助手使用。
下面的代码不起作用,但我认为它显示了我正在尝试做的事情。
public class NotificationProvider
{
public List<Notification> Notifications { get; set; }
private Controller _controller;
public NotificationProvider(Controller controller /* How to pass controller instance? */)
{
_controller = controller;
if (_controller.TempData["Notifications"] != null)
{
Notifications = (List<Notification>)controller.TempData["Notifications"];
_controller.TempData["Notifications"] = null;
}
}
public void ShowNotification(NotificationType notificationType, string message)
{
Notification notification = new Notification();
notification.Type = notificationType;
notification.Message = message;
Notifications.Add(notification);
_controller.TempData["Notifications"] = Notifications;
}
public void LoadNotifications()
{
_controller.ViewData["Notifications"] = Notifications;
}
}
在每个控制器中都有一个 NotificationProvider 实例:
public class HomeController
{
private NotificationProvider notificationProvider;
public HomeController()
{
notificationProvider = new NotificationProvider(/* Controller instance */);
notificationProvider.LoadNotifications();
}
}
问题:
如何将控制器实例传递给 NotificationProvider 类,以便它可以访问 TempData 和 ViewData 对象。或者如果可能的话,我怎样才能直接从 NotificationProvider 实例访问这些对象?