我有一个看起来像这样的 WPF 代码。
public class AlphaProductesVM : BaseModel
{
private ObservableCollection<Alphabetical_list_of_product> _NwCustomers;
private int i = 0;
public AlphaProductesVM ()
{
_NwCustomers = new ObservableCollection<Alphabetical_list_of_product>();
var repository = new NorthwindRepository();
repository
.GetAllProducts()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(AddElement);
}
public void AddElements(IEnumerable<Alphabetical_list_of_product> elements)
{
foreach (var alphabeticalListOfProduct in elements)
{
AddElement(alphabeticalListOfProduct);
}
}
public ObservableCollection<Alphabetical_list_of_product> NwCustomers
{
get { return _NwCustomers; }
set { _NwCustomers = value; }
}}
我使用 Unity 来解决上面的 AlphaProductesVM
。当使用 PRISM 和 UnityBootstrapper 发现模块时,这是即时的。在运行时 .ObserveOn(SynchronizationContext.Current)
抛出异常并且 SynchronizationContext.Current
中有一个 null
值。
最佳答案
SynchronizationContext.Current属性只会在主线程上调用时返回一个值。
如果你需要使用 SynchronizationContext 除了主线程中的对象,你可以传递 SynchronizationContext与主线程关联的实例到需要它的类作为依赖项。
如果您选择此解决方案,您可以注册 SynchronizationContext从 SynchronizationContext.Current 获得的对象主线程上的属性作为容器中的单例。这样所有对 SynchronizationContext 的请求从那时起,容器将自动满足单例:
// Must run in the main thread
container.RegisterInstance(SynchronizationContext.Current);
关于c# - 在 WPF 中使用 Unity 解析时,SynchronizationContext.Current 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9377290/