Click or drag to resize

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.

  1. Make sure the target type either derives from an AsyncInit base class or implements an AsyncInit interface:

    C#
    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; }
    }
  2. Make sure the target type also derives from a base class or implements an interface that will be used for resolving it:

    C#
    interface IUniversalAnswerService
    {
        int Answer { get; }
    }
    
    class UniversalAnswerService : CancelableAsyncInitBase<UniversalAnswerService>, IUniversalAnswerService
    {
        //...
    }

    In this example IUniversalAnswerService is the source type and UniversalAnswerService is the target type.

  3. Import the Unity Container Async Extensions namespace:

    C#
    using Ditto.AsyncInit.Unity;
  4. Register the mapping for asynchronous resolution:

    C#
    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.

See Also