我对这类事情采取的方法是在解决方案中创建一个中心项目;可以称为 Core.UI(或任何你喜欢的)。在那里,我创建了一个在容器中注册为单例的类,该类在应用程序启动时加载所需的数据(通过 Initialize 调用;参见代码)。这通常被称为服务。
您可以根据需要灵活地加载数据。在应用程序加载时,或第一次访问属性时。我是提前做的,因为数据并不大,而且不会经常变化。您甚至可能还想在这里考虑某种缓存机制。
我也为产品做过类似的事情。以下是美国州代码。
public class StateListService : IStateListService // The interface to pass around
{
IServiceFactory _service_factory;
const string country = "United States";
public StateListService(IServiceFactory service_factory)
{
_service_factory = service_factory;
Initialize();
}
private void Initialize()
{
// I am using WCF services for data
// Get my WCF client from service factory
var address_service = _service_factory.CreateClient<IAddressService>();
using (address_service)
{
try
{
// Fetch the data I need
var prod_list = address_service.GetStateListByCountry(country);
StateList = prod_list;
}
catch
{
StateList = new List<AddressPostal>();
}
}
}
// Access the data from this property when needed
public List<AddressPostal> StateList { get; private set; }
}
编辑:
要将上述内容注册为 Prism 6 中的单例,请将这行代码添加到用于初始化容器的方法中。通常在引导程序中。
RegisterTypeIfMissing(typeof(IStateListService), typeof(StateListService), true);