我不会在后面的代码中实例化对象。我所做的是调用一个实例化获取对象的服务——它用数据库中的数据实例化它们。我还在母版页中公开了该服务,并像这样引用它:
IUser _user = (Page.Master as MasterBase).RegistrationService.GetPersonFromEmailAddress(txtUser.text);
当然,您应该检查以确保 (Page.Master as MasterBase) 不为空......
按要求编辑
我创建了一个基础母版页,所有其他站点母版页都必须继承自该母版页。在这个基本母版页的构造函数中,我实例化了所有必要的服务。当然,如果服务没有在整个站点中使用,它们可以在不同的、更合适的部分通用母版页上实例化。
public readonly IRegistration RegistrationService;
public readonly IEventService EventService;
public readonly IEmailSendingService EmailService;
private readonly IMenuService _menuService;
public MasterBase()
{
RegistrationService = new BusinessLogic.Registration(DatabaseConnectionString);
EventService = new EventService(DatabaseConnectionString);
var fromAddress = ConfigurationManager.AppSettings["Webmaster"];
var defaultToEmailAddress = ConfigurationManager.AppSettings["toEmail"];
EmailService = new EmailSendingService(BaseUrl, fromAddress, defaultEmailAddress);
_menuService = new MenuService(DatabaseConnectionString);
}
如上所述,网站上使用的任何母版页都将从基础继承:
public partial class MasterContent : MasterBase
任何引用母版页的 UI 页面(在我的例子中几乎全部)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="activities.aspx.cs" Inherits="activities" MasterPageFile="~/MasterContent.Master" %>
现在可以访问后面代码中的不同服务:
IUser _user = (Page.Master as MasterBase).RegistrationService.GetPersonFromEmailAddress(txtUser.text);
正如下面评论中提到的,不同的 UI 页面确实与基本母版页紧密耦合,但我不知道在一般的 ASP.NET Web 表单应用程序中有什么更好的方法来做到这一点。它减少了在每个 UI 页面上实例化服务的需要,并且从特定于项目的角度来看,使所有母版页都继承自该基本页面是可以接受的。