Skip to content

async/await in service registration or service resolution. #2353

@aspnet-hello

Description

@aspnet-hello

From @Antaris on Wednesday, October 14, 2015 3:10:50 AM

Is it possible to support async/await and Task based service resolution? I'll walk you through an example:

public class WorkContext : IWorkContext
{
  public WorkContext(ISecurityContext securityContext)
  {
    SecurityContext = securityContext;
  }

  public ISecurityContext SecurityContext { get; private set; }
}

public class WorkContextFactory : IWorkContextFactory
{
  private readonly ISecurityContextFactory _securityContextFactory;

  public WorkContextFactory(ISecurityContextFactory securityContextFactory)
  {
    _securityContextFactory = securityContextFactory;
  }

  public async Task<IWorkContext> CreateWorkContext(CancellationToken cancellationToken = default(CancellationToken))
  {
    // Get the security context for the current user
    var securityContext = await _securityContextFactory.GetForCurrentUser(cancellationToken);

    return new WorkContext(securityContext);
  }
}

In my example above, I'm defining some implementations of abstractions provided by my framework. In a dependency, the ISecurityContextFactory I implement a Task-based async/await model because I don't know that the actual implementation might do some DB work to say load the current user information.

When I come to wire up my services, I want to utilise my WorkContextFactory to build my type (seperation of concerns), so I might do something like the following:

yield return ServiceDescriptor.Scoped<IWorkContextFactory, WorkContextFactory>();
yield return ServiceDescriptor.Scoped<IWorkContext>(sp => sp.GetService<IWorkContextFactory>().CreateWorkContext().Result);

Obviously at the moment, I'm having to block until I get the result of Task<IWorkContext>, but it would be great if I could do something like:

yield return ServiceDescriptor.Scoped<IWorkContext>(sp => sp.GetService<IWorkContextFactory>().CreateWorkContext());

And have the DI system understand the Task result and await.

Is this possible?

Copied from original issue: aspnet/DependencyInjection#303

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions