Open sandboxFocus

Class RunTimeServiceLocator

A process-wide registry of run-time services, which the code generated by PostSharp uses when a dependency was not supplied.

Inheritance
RunTimeServiceLocator
Namespace: PostSharp.Extensibility
Assembly: PostSharp.dll
Syntax
public static class RunTimeServiceLocator
Remarks

When a class receives a dependency from its constructors, because an aspect requested it with ImportDependencyAdviceInstance, and the constructor receives null for that dependency, the generated code resolves the dependency with GetRequiredService<T>(), or with GetService<T>() when the dependency is optional. This is the case when the object is created with new instead of by a dependency injection container.

A service is registered as a factory, which runs each time the service is resolved. A factory can therefore return a singleton, a new object, or an object that depends on the context, for instance on an AsyncLocal<T> that the application sets.

This class is not a dependency injection container: it has no scopes and does not dispose the services. Register the services at startup, before the objects that need them are created.

Properties

Name Description
ServiceProvider

Gets an IServiceProvider that resolves the services registered in RunTimeServiceLocator. Its GetService(Type) method returns null when no service of the requested type is registered, and throws InvalidCastException when the factory returns an object that is not assignable to the requested type.

Methods

Name Description
GetRequiredService<T>()

Resolves a service of type T by running its factory, and throws an exception when no service is available.

GetService<T>()

Resolves a service of type T by running its factory.

RegisterService(Type, Func<object>)

Registers the factory of a service, or replaces the factory registered for the same type.

RegisterService<T>(Func<T>)

Registers the factory of a service of type T, or replaces the factory registered for the same type.

TryRegisterService<T>(Func<T>)

Registers the factory of a service of type T unless a factory is already registered for this type, without running the registered factory. A library uses it to provide a default that the application can replace, before or after.

See Also