c# - 在 WPF 中使用 Unity 解析时,SynchronizationContext.Current 为空

标签 c# wpf mvvm unity-container system.reactive

我有一个看起来像这样的 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与主线程关联的实例到需要它的类作为依赖项

如果您选择此解决方案,您可以注册 SynchronizationContextSynchronizationContext.Current 获得的对象主线程上的属性作为容器中的单例。这样所有对 SynchronizationContext 的请求从那时起,容器将自动满足单例:

// Must run in the main thread
container.RegisterInstance(SynchronizationContext.Current);

关于c# - 在 WPF 中使用 Unity 解析时,SynchronizationContext.Current 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9377290/

相关文章:

C# Getter setter

c# - 可能的错误(?)xsockets.net控制台服务器

wpf - 如何绑定(bind)到 ControlTemplate 中的 SelectedItem 属性?

wpf - 将 TextBox IsEnabled 绑定(bind)到 VM 的属性

c# - 代码转换

c# - 文本框值不保存

c# - 在 C# 的 Windows 窗体中的 PictureBox 中显示 System.Windows.Media.Imaging.BitmapSource

wpf - 在 WPF 文本框中使用箭头键 (C#)

c# - Xamarin.Forms - C# 代码中的 View 到 View 绑定(bind)?

wpf - WPF模型- View - View 模型工具包