Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splat.Locator Multiple views for one ViewModel

Tags:

c#

uwp

reactiveui

I use the following code

 Splat.Locator.Current.GetService(...) 

to get view for view model. But this method allows to use only one view for one view model. But I have to show 1 data (view model) in multiple views. Is it possible by Splat.Locator?

like image 301
Alexander Kalenteenkov Avatar asked Feb 23 '26 12:02

Alexander Kalenteenkov


1 Answers

The Register() and GetService() have a contract argument, which you can use as a key to get the implementation you need.

Example, where "giveMeBar"/"giveMeBaz" are values for the contract argument:

using System;
using Splat;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main()
        {
            // Register
            Locator.CurrentMutable.Register(() => new Bar(), typeof(IFoo), "giveMeBar");
            Locator.CurrentMutable.Register(() => new Baz(), typeof(IFoo), "giveMeBaz");

            // Resolve
            var bar = Locator.Current.GetService<IFoo>("giveMeBar");
            var baz = Locator.Current.GetService<IFoo>("giveMeBaz");

            // Which types did we get?
            Console.WriteLine(bar);
            Console.WriteLine(baz);
            Console.ReadLine();

            // Outputs:
            // ConsoleApp1.Bar
            // ConsoleApp1.Baz
        }        
    }

    internal interface IFoo { }
    internal class Bar : IFoo { }
    internal class Baz : IFoo { }
}
like image 63
Magnus Avatar answered Feb 25 '26 01:02

Magnus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!