Do we need to use async/await keyword in controller? - c#

I have a user controller like this:
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public async Task<User> Get(int id, CancellationToken cancellationToken)
{
return await _userService.GetUserById(id, cancellationToken);
}
}
and a user service:
public class UserService : IUserService
{
public async Task<User> GetUserById(int id, CancellationToken cancellationToken)
{
return await _dbContext.Users.Where(a => a.Id == id).FirstOrDefaultAsync(cancellationToken);
}
}
In UserService I have an async method that returns a user by Id.
My question is, do we need to use async/await keyword in controller or is using async/await in UserService enough?
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
public Task<User> Get(int id, CancellationToken cancellationToken)
{
return _userService.GetUserById(id, cancellationToken);
}
}

If you're only awaiting one thing, as the last line of an async method, and returning the result directly or not at all (i.e. not doing anything non-trivial with the result), then yes you can elide the await, by removing the async and await parts; this avoids a bit of machinery, but it means that if the method you're calling faults synchronously (specifically: it throws an exception rather than returning a task that reports a fault state), then the exception will surface slightly differently.
Avoiding this state machine can matter if you're in an inner loop, for example in the middle of IO code that gets called many many times per operation and you need to optimize it, but: that doesn't apply here - you're at the top of a controller. Honestly, it doesn't need optimizing: just use the async/await: it'll be more consistently correct.

Yes, in order to consume the service method asynchronously, you'll need to make the Controller asynchronous also.
It's "Async All the Way" ...
https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#async-all-the-way

Related

StartAsync is called twice on the same IHostedService

As the title states, when I register multiple instances of IHostedService, it calls StartAsync twice on the first instance, but not the second, but it does call both constructors.
Program.cs
services.AddSingleton<IHostedService, ProductService>(provider => (ProductService)provider.GetService<IProductService>()!);
services.AddSingleton<IProductService, ProductService>();
services.AddSingleton<IHostedService, ProductService>(provider => (ProductService)provider.GetService<IProductService>()!);
services.AddSingleton<IProductService, ProductService>();
ProductService.cs
public class ProductService : IProductService, IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken) { }
public async Task StopAsync(CancellationToken cancellationToken) { }
}
How can I solve this? I need multiple instances of ProductService (name changed for simplicity).
To spin up 2 hosted services of the same type, it suffices to register the same service 2 times with a transient lifetime scope.
Each will have a constructor call and a StartAsync call, which you can verify via the value of the Guid field in the example ProductService below.
services.AddTransient<IHostedService, ProductService>();
services.AddTransient<IHostedService, ProductService>();
This post explains that a hosted service used to be a long lived transient with the behavior of a singleton.
public class ProductService : IHostedService
{
private readonly Guid _id = Guid.NewGuid();
public ProductService( /* Any dependencies */ )
{ }
public Task StartAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken)
=> Task.CompletedTask;
}
Well, it's hard to say without your implementation of StartAsync but StartAsync method is intended to be non-blocking.
Schedule any work you need and then finish StartAsync.
StartAsync method of the second instance is waiting for the first one to finish starting before it tries to start the next one.
public Task StartAsync(CancellationToken cancellationToken)
{
Task.Run(() => SomeWork(cancellationToken));
return Task.CompletedTask;
}
You can use a factory to maintain n number of instances. i just added a sample
class ProductFactory : IProductFactory
{
private readonly Dictionary<string, ProductService> _productService ;
public void Register(string name, ProductService productService)
{
_productService[name] = productService;
}
public HttpClient Resolve(string name)
{
return _productService[name];
}
}
var factory = new ProductFactory();
factory.Register("p1", new ProductService());
factory.Register("p2", new ProductService());
services.AddSingleton<IProductFactory>(factory);
public ProductController(IProductFactory factory)
{
_productFactory = factory.Resolve("p1");
}
You can use factory not to start .

Does it make sense to save and commit changes in INotificationHandler in MediatR?

I'm looking for a solution to use INotification in MediatR, what I'm trying to do is handling the commits and changes in INotificationHandler, instead of IRequestHandler.
Does it make sense to do so?
Product-> AddProduct->ProductWasAdded.
public class AddProductCommandHandler : IRequestHandler<AddProductCommand, Result<ProductTypeId>>
{
private readonly DbContext _writeContext;
private readonly IMediator _mediator;
public AddProductCommandHandler( DbContext writeContext, IMediator mediator )
{
_writeContext = writeContext;
_mediator = mediator;
}
public async Task<Result<ProductTypeId>> Handle( AddProductCommand request, CancellationToken cancellationToken )
{
//Logics ommitedfor bravety
await _mediator.Publish( new ProductWasAddedEvent(product), cancellationToken );
}
}
and in INotificationHandler:
public class ProductWasAddedEvent:INotification
{
public Product Product { get; }
public ProductWasAddedEvent(Product product)
{
Product= product;
}
}
Finally in INotificationHandler:
public class ProductEvents:INotificationHandler<ProductWasAddedEvent>
{
private readonly DbContext _writeContext;
public ProductEvents( DbContext writeContext )
{
_writeContext = writeContext;
}
public async Task Handle( ProductWasAddedEvent notification, CancellationToken cancellationToken )
{
await _writeContext.Products.AddAsync( notification.Product, cancellationToken );
await _writeContext.SaveChangesAsync( cancellationToken );
}
}
I guess it highly depends on whether you're handling the "events" in separate microservices or perhaps if you plan on sending them through a real message bus (eg. RabbitMQ, Kafka).
If you're handling everything in memory in a single process, you might be good with your current approach.
However, resiliency and fault tolerance are not exactly guaranteed. For that you might want to look at the Outbox pattern. It would let you to create a single transaction on your DB, persist your data AND the messages/events you want to dispatch. Then a separate background service will take care of sending them.

.net core web api controller life cycle

hello I understand the life cycle of injected service like scoped that after the request is finished the service is unavailable. But the parameter (like myObject in the example) when their are destroyed? If i pass this parameter to long async task and I don't await the result I could have some problem of null in the task?
public class mycontroller : ControllerBase
{
private MyService _myservice;
public mycontroller(MyService myservice)
{
_myservice = myservice;
}
[HttpPost]
public IActionResult Post([FromBody] MyObject myObject)
{
_myservice.dosomethinglongasync(myObject);
return OK();
}
}
The task will continue to hold a reference onto myObject until it's completed. You should not face an issue that it's destroyed beforehand.
But(!) this is a bad design. You can not check the task for completion, etc. Firing async tasks without awaiting them somewhere is no good practice.

ASP.NET Core 5 - How to have optional dependencies?

I'm developing a middleware which I would like to have an optional dependency on a internal logging library. In another words, if MyLoggingService is registered, great!, else, life goes on and ill log to console.
But by declaring public async Task Invoke(HttpContext httpContext, MyLoggingService logger), I get a runtime error saying that it was not registred. I tried setting a default value to null but that didn't work. Also, because its a middleware, I can't overload the Invoke method.
Is there a solution other than requesting the service collection and resolving the dependency myself?
The answer is incredibly simple:
public async Task Invoke(HttpContext httpContext, MyLoggingService logger = null)
Instead of making dependencies optional, consider:
Programming to an abstraction, e.g. IMyLoggingService
Register a Null Object implementation
For instance:
public class CustomMiddleware1 : IMiddleware
{
private readonly IMyLoggingService logger;
public CustomMiddleware1(IMyLoggingService logger) => this.logger = logger;
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
this.logger.Log("Before");
await next(context);
this.logger.Log("After");
}
}
Null Object implementation:
public sealed class NullMyLoggingService : IMyLoggingService
{
public void Log(LogEntry e) { }
}
Registrations:
services.AddSingleton<IMyLoggingService>(new NullMyLoggingService());
app.Use<CustomMiddleware1>();
The call to AddSingleton<IMyLoggingService>(new NullMyLoggingService()) ensures a registration for IMyLoggingService always exists. This prevents complexity in consumers, who would otherwise have to add conditional logic for the case that the logger isn't present.
This null implementation can be replaced by simply adding a second IMyLoggingService after the first:
services.AddScoped<IMyLoggingService, DbMyLoggingService>();
app.Use<CustomMiddleware1>();

Cancellation Token Injection

I'd like to be able to pass cancellation tokens via dependency injection instead of as parameters every time. Is this a thing?
We have an asp.net-core 2.1 app, where we pass calls from controllers into a maze of async libraries, handlers and other services to fulfil the byzantine needs of the fintech regulatory domain we service.
At the top of the request, I can declare that I want a cancellation token, and I'll get one:
[HttpPost]
public async Task<IActionResult> DoSomeComplexThingAsync(object thing, CancellationToken cancellationToken) {
await _someComplexLibrary.DoThisComplexThingAsync(thing, cancellationToken);
return Ok();
}
Now, I want to be a good async programmer and make sure my cancellationToken gets passed to every async method down through the call chain. I want to make sure it gets passed to EF, System.IO streams, etc. We have all the usual repository patterns and message passing practices you'd expect. We try to keep our methods concise and have a single responsibility. My tech lead gets visibly aroused by the word 'Fowler'. So our class sizes and function bodies are small, but our call chains are very, very deep.
What this comes to mean is that every layer, every function, has to hand off the damn token:
private readonly ISomething _something;
private readonly IRepository<WeirdType> _repository;
public SomeMessageHandler(ISomething<SomethingElse> something, IRepository<WeirdType> repository) {
_something = something;
_repository = repository;
}
public async Task<SomethingResult> Handle(ComplexThing request, CancellationToken cancellationToken) {
var result = await DoMyPart(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
result.SomethingResult = await _something.DoSomethingElse(result, cancellationToken);
return result;
}
public async Task<SomethingResult> DoMyPart(ComplexSubThing request, CancellationToken cancellationToken) {
return await _repository.SomeEntityFrameworkThingEventually(request, cancellationToken);
}
This goes on ad infinitum, as per the needs of our domain complexity. It seems like CancellationToken appears more times in our codebase than any other term. Our arg lists are often already too long (i.e. more than one) as it is, even though we declare a million object types. And now we have this extra little cancellation token buddy hanging around in every arg list, every method decl.
My question is, since Kestrel and/or the pipeline gave me the token in the first place, it'd be great if I could just have something like this:
private readonly ISomething _something;
private readonly IRepository<WeirdType> _repository;
private readonly ICancellationToken _cancellationToken;
public SomeMessageHandler(ISomething<SomethingElse> something, ICancellationToken cancellationToken) {
_something = something;
_repository = repository;
_cancellationToken = cancellationToken;
}
public async Task<SomethingResult> Handle(ComplexThing request) {
var result = await DoMyPart(request);
_cancellationToken.ThrowIfCancellationRequested();
result.SomethingResult = await _something.DoSomethingElse(result);
return result;
}
public async Task<SomethingResult> DoMyPart(ComplexSubThing request) {
return await _repository.SomeEntityFrameworkThingEventually(request);
}
This would then get passed around via DI composition, and when I had something that needs the token explicitly I could do this:
private readonly IDatabaseContext _context;
private readonly ICancellationToken _cancellationToken;
public IDatabaseRepository(IDatabaseContext context, ICancellationToken cancellationToken) {
_context = context;
_cancellationToken = cancellationToken;
}
public async Task<SomethingResult> DoDatabaseThing() {
return await _context.EntityFrameworkThing(_cancellationToken);
}
Am I nuts? Do I just pass the damn token, every damn time, and praise the async gods for the bounty that has been given? Should I just retrain as a llama farmer? They seem nice. Is even asking this some kind of heresy? Should I be repenting now? I think for async/await to work properly, the token has to be in the func decl. So, maybe llamas it is
First of all, there are 3 injection scopes: Singleton, Scoped and Transient. Two of those rule out using a shared token.
DI services added with AddSingleton exist across all requests, so any cancellation token must be passed to the specific method (or across your entire application).
DI services added with AddTransient may be instantiated on demand and you may get issues where a new instance is created for a token that is already cancelled. They'd probably need some way for the current token to be passed to [FromServices] or some other library change.
However, for AddScoped I think there is a way, and I was helped by this answer to my similar question - you can't pass the token itself to DI, but you can pass IHttpContextAccessor.
So, in Startup.ConfigureServices or the extension method you use to register whatever IRepository use:
// For imaginary repository that looks something like
class RepositoryImplementation : IRepository {
public RepositoryImplementation(string connection, CancellationToken cancellationToken) { }
}
// Add a scoped service that references IHttpContextAccessor on create
services.AddScoped<IRepository>(provider =>
new RepositoryImplementation(
"Repository connection string/options",
provider.GetService<IHttpContextAccessor>()?.HttpContext?.RequestAborted ?? default))
That IHttpContextAccessor service will be retrieved once per HTTP request, and that ?.HttpContext?.RequestAborted will return the same CancellationToken as if you had called this.HttpContext.RequestAborted from inside a controller action or added it to the parameters on the action.
I think you are thinking in a great way, I do not think you need to regret or repent.
This is a great idea, I also thought about it, and I implement my own solution
public abstract class RequestCancellationBase
{
public abstract CancellationToken Token { get; }
public static implicit operator CancellationToken(RequestCancellationBase requestCancellation) =>
requestCancellation.Token;
}
public class RequestCancellation : RequestCancellationBase
{
private readonly IHttpContextAccessor _context;
public RequestCancellation(IHttpContextAccessor context)
{
_context = context;
}
public override CancellationToken Token => _context.HttpContext.RequestAborted;
}
and the registration should be like this
services.AddHttpContextAccessor();
services.AddScoped<RequestCancellationBase, RequestCancellation>();
now you can inject RequestCancellationBase wherever you want, and the better thing is that you can directly pass it to every method that expects CancellationToken this is because of public static implicit operator CancellationToken(RequestCancellationBase requestCancellation)
this solution helped me, hope it is helpful for you also

Categories

Resources