How To Register an Asynchronous Type Mapping |
This topic details the steps necessary for registering a mapping to an asynchronously initialized type with a Unity container.
Make sure the target type either derives from an AsyncInit base class or implements an AsyncInit interface:
using Ditto.AsyncInit; class UniversalAnswerService : CancelableAsyncInitBase<UniversalAnswerService> { private UniversalAnswerService() : base(null) { } protected override async Task InitAsync(CancellationToken cancellationToken) { await Task.Delay(TimeSpan.FromDays(7500000 * 365.25), cancellationToken); Answer = 42; } public int Answer { get; private set; } }
Make sure the target type also derives from a base class or implements an interface that will be used for resolving it:
interface IUniversalAnswerService { int Answer { get; } } class UniversalAnswerService : CancelableAsyncInitBase<UniversalAnswerService>, IUniversalAnswerService { //... }
In this example IUniversalAnswerService is the source type and UniversalAnswerService is the target type.
Import the Unity Container Async Extensions namespace:
using Ditto.AsyncInit.Unity;
Register the mapping for asynchronous resolution:
container.RegisterAsyncType<IUniversalAnswerService, UniversalAnswerService>();
The target type may now be resolved asynchronously via the source type.
Unity Container Async Extensions provide support for advanced registration scenarios through overloads of RegisterAsyncType.