Ioc Class

Definition

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!");
public sealed class Ioc : IServiceProvider
type Ioc = class
    interface IServiceProvider
Public NotInheritable Class Ioc
Implements IServiceProvider
Inheritance
Ioc
Implements

Constructors

Ioc()

Properties

Default

Gets the default Ioc instance.

Methods

ConfigureServices(IServiceProvider)

Initializes the shared IServiceProvider instance.

GetRequiredService<T>()

Resolves an instance of a specified service type.

GetService(Type)
GetService<T>()

Tries to resolve an instance of a specified service type.

Applies to