Microsoft.Extensions.DependencyInjection

Namespace for .NET dependency injection services.

Microsoft.Extensions.DependencyInjection

interface IServiceProvider

Represents a contract for a service locator that can be used to resolve services.

This interface is the core of the dependency injection container, allowing consumers to obtain instances of registered services.

Members

  • object GetService(Type serviceType)

    Retrieves an instance of the specified service type from the service provider.

    If the service is not registered or cannot be resolved, it returns null.

    Parameters:

    • serviceType: The System.Type of the service to retrieve.

    Returns:

    An instance of the service type, or null if the service is not found.

    Declaration:
    public object GetService(Type serviceType);
    Assembly:
    Microsoft.Extensions.DependencyInjection.Abstractions.dll

Remarks

IServiceProvider is the read-only interface representing a resolved set of services. It is typically implemented by a dependency injection container.

When you need to access a service that has been registered with an IServiceCollection, you use an IServiceProvider to get an instance of that service.

A common pattern is to build an IServiceProvider from an IServiceCollection and then use it to resolve services.

IServiceProvider should be disposed of when it is no longer needed, especially if it owns disposable services.

Usage Example

Here's a simple example of how you might use IServiceProvider:


// Assume services is an IServiceCollection that has been configured
// For example:
// services.AddTransient<IMyService, MyService>();

var serviceProvider = services.BuildServiceProvider();

// Resolve an instance of IMyService
IMyService myService = serviceProvider.GetService<IMyService>();

if (myService != null)
{
    // Use myService
    myService.DoSomething();
}

// Dispose the service provider if it owns disposable services
// In a typical ASP.NET Core application, the framework handles this.
// For standalone applications:
// using (var serviceProvider = services.BuildServiceProvider())
// {
//     var myService = serviceProvider.GetService<IMyService>();
//     // ...
// }
                    

Related Types