Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SynchronizationContext.Current is null on resolving with Unity in WPF

I have a WPF Code which looks something like this.

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; }
    }}

I use Unity to Resolve the above AlphaProductesVM. This is instant when the Module is discovered using PRISM and the UnityBootstrapper. At runtime .ObserveOn(SynchronizationContext.Current) throws an exception and SynchronizationContext.Current has a null value in it.

like image 596
Arshad Badar Khan Avatar asked Oct 09 '22 14:10

Arshad Badar Khan


1 Answers

The SynchronizationContext.Current property will only return a value when invoked on the main thread.

If you need to use a SynchronizationContext object in threads other than the main thread, you could pass the SynchronizationContext instance associated to the main thread to the classes that need it as a dependency.

If you choose this solution, you could register the SynchronizationContext object obtained from the SynchronizationContext.Current property on the main thread as a singleton in your container. That way all requests for a SynchronizationContext from that point on will automatically be satisfied by the container with the singleton:

// Must run in the main thread
container.RegisterInstance(SynchronizationContext.Current);
like image 120
Enrico Campidoglio Avatar answered Oct 12 '22 12:10

Enrico Campidoglio