Is the lack of the async keyword in interfaces a DI violation in C # 5.0?

I was happy to create my first C # 5.0 application, and I wanted to use the async / await keywords to facilitate asynchronous data calls.

I am a little puzzled that the interfaces do not allow the async keyword to be part of the contract, since the await keyword only works for asynchronous labels. This would mean that calling asynchronous methods through interface references is not possible. This also applies to abstract methods. Am I missing something? This would mean that my regular DI stuff would no longer work:

IAsyncRepository<T> { Task<IList<T>> GetAsync(); // no 'async' allowed } abstract class AsyncRepositoryBase<T> { public abstract Task<IList<T>> GetAsync(); // no 'async' allowed 

//Client code:

 IAsyncRepository<Model> repo = ioc.Resolve<IAsyncRepository<Model>>(); var items = await repo.GetAsync(); // DOOOOOH, will not compile! 

This is my current solution:

 public abstract class AsyncRepositoryBase<T> { protected Task<IList<T>> _fetcherTask; protected AsyncRepositoryBase(Task<IList<T>> fetcherTask) { _fetcherTask = fetcherTask; } public virtual async Task<IList<T>> GetASync() { return await _fetcherTask; } } 

Do I have to choose between abstraction and langauge function? Please tell me I'm missing something.

+6
source share
1 answer

Keyword wait only works for asynchronous tagged methods

Your problem is there. Although await should be inside the async method, it can wait for any task, regardless of whether it is implemented through async or not.

For instance:

 interface IFoo { Task BarAsync(); } class Foo : IFoo { public async Task BarAsync() { // Implemented via async/await in this case. // You could also have implemented it without async/await. } } // ... async void Test() { IFoo foo = ... ; await foo.BarAsync(); // Works no matter how BarAsync is implemented. } 

Regarding your syntax error: await repo.GetAsync(); // DOOOOOH, will not compile! await repo.GetAsync(); // DOOOOOH, will not compile! - did you forget to mark the method containing this piece of code as async (you do not need to mark IAsyncRepository.GetAsync as async )?

+7
source

All Articles