【问题标题】:When is the best time to load lookup tables using prism/unity?使用 prism/unity 加载查找表的最佳时间是什么时候?
【发布时间】:2017-01-02 23:55:51
【问题描述】:
我正在寻找一些关于使用 Prism Unity 加载查找表(例如状态代码)的良好设计的建议?我的视图库以域为中心,并且我有传递 IUnityContainer 的模块。在初始化部分,我向容器注册了 RegisterType,例如 IStateCode、StateCode。
我应该注册Type,然后加载状态对象,然后使用RegisterInstance吗?这应该在每个域(dll)中完成还是应该集中加载表一次,在哪里?我曾考虑在主窗口的 Load 中加载查找表,但我必须引用该模块中的所有查找类。如果我使用一个中心位置来加载查找表,我不必担心查找表为空并且它位于一个区域中。怎么样?
【问题讨论】:
标签:
c#
architecture
unity-container
prism-6
【解决方案1】:
我对这类事情采取的方法是在解决方案中创建一个中心项目;可以称为 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);