ghuntley / reactiveui-samples

0 stars 0 forks source link

Service Location #3

Open ghuntley opened 9 years ago

ghuntley commented 9 years ago

Might be able to get away with just pointing users towards another sample in a README.md

ghuntley commented 9 years ago

Service Location

ReactiveUI (via Splat) provides a simple service location implementation that is optimized for Desktop and Mobile applications, while still remaining reasonably flexible. To get a type:

var toaster = Locator.Current.GetService<IToaster>();
var allToasterImpls = Locator.Current.GetServices<IToaster>();

Locator.Current is a static variable that can be set on startup, to adapt Splat to other DI/IoC frameworks. This is usually a bad idea.

The default implementation of Service Location also allows new types to be registered at runtime.

// Create a new Toaster any time someone asks
Locator.CurrentMutable.Register(() => new Toaster(), typeof(IToaster));

// Register a singleton instance
Locator.CurrentMutable.RegisterConstant(new ExtraGoodToaster(), typeof(IToaster));

// Register a singleton which won't get created until the first user accesses it
Locator.CurrentMutable.RegisterLazySingleton(() => new LazyToaster(), typeof(IToaster));