CommunityToolkit.Mvvm.DependencyInjection Namespace

Classes

Ioc

A type that facilitates the use of the IServiceProvider type. The Ioc provides the ability to configure services in a singleton, thread-safe service provider instance, which can then be used to resolve service instances. The first step to use this feature is to declare some services, for instance:

public interface ILogger
{
    void Log(string text);
}
public class ConsoleLogger : ILogger
{
    void Log(string text) => Console.WriteLine(text);
}

Then the services configuration should then be done at startup, by calling the ConfigureServices(IServiceProvider) method and passing an IServiceProvider instance with the services to use. That instance can be from any library offering dependency injection functionality, such as Microsoft.Extensions.DependencyInjection. For instance, using that library, ConfigureServices(IServiceProvider) can be used as follows in this example:

Ioc.Default.ConfigureServices(
    new ServiceCollection()
    .AddSingleton<ILogger, Logger>()
    .BuildServiceProvider());

Finally, you can use the Ioc instance (which implements IServiceProvider) to retrieve the service instances from anywhere in your application, by doing as follows:

Ioc.Default.GetService<ILogger>().Log("Hello world!");