Click or drag to resize

How To Register an Asynchronous Type

This topic details the steps necessary for registering an asynchronously initialized type with a Unity container.

  1. Make sure the 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. Import the Unity Container Async Extensions namespace:

    C#
    using Ditto.AsyncInit.Unity;
  3. Register the type for asynchronous resolution:

    C#
    container.RegisterAsyncType<UniversalAnswerService>();

The registered type may now be resolved asynchronously.

Unity Container Async Extensions provide support for advanced registration scenarios through overloads of RegisterAsyncType.

See Also