0

In my API controller I'm define a string variable called log and I need to set value to that variable from the each calling methods.

for example, here is my controller method.

[HttpGet][Route("getData")] public async Task < IActionResult > GetPayementData() {
  string log = DateTime.Now.ToString();
  log = log + " This is Controller ";
  var data = await _paymentRepo.DataTransfer(log);
  return Ok(data);
}

here, I'm passing log variable value into a DataTransfer repository method and from there I'm again assign some value for it. This is how DataTransfer() method.

public async Task < sampleModel > DataTransfer(string log) {
  log = log + DateTime.Now.ToString() + "This is Repository";
  var sampleData = new sampleModel();
  sampleData.ID = 1000;
  sampleData.Name = "Stackoverflow";
  return sampleData;
}

Finally, I need to get the log variable value from the controller, all after set value from the each methods to log variable. for example I need log final variable value as,

3/22/2022 9:55:07 PM This is Controller 3/22/2022 9:55:11 PM This is Repository

I tried to use ref

public async Task <sampleModel> DataTransfer(ref string log) {

}

But I can't use ref or out with the async methods. How can I resolve this. please be noted inside the repo method, which calling several sub methods and inside the each methods I need to set value to log variable.

NTB_BOY
  • 23
  • 3
  • can't you return it as part of your sampledata ? – auburg Mar 22 '22 at 16:34
  • @auburg no its difficult, because some methods inside calling repo methods not have return type, but those set values to log variable – NTB_BOY Mar 22 '22 at 16:38
  • what i meant was can you not return the log string as part of the other data you return ? – auburg Mar 22 '22 at 16:41
  • If the `log` is the classic log message to be written to the console/file/etc, then you may want to use "structured logging" with dependency injection as described here https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0 This will allow you to write log without explicitly passing `log` parameter to every method. – Serg Mar 22 '22 at 16:42
  • @Serg I used this as a sample, my actual scenario is not doing the logging kind of thing, I just used this a example – NTB_BOY Mar 22 '22 at 16:47
  • 1
    You can check this [answer](https://stackoverflow.com/questions/20868103/ref-and-out-arguments-in-async-method). As you can see this is not possible. – Azzy Elvul Mar 22 '22 at 16:52
  • Related: [How to write an async method with out parameter?](https://stackoverflow.com/questions/18716928/how-to-write-an-async-method-with-out-parameter) – Theodor Zoulias Mar 22 '22 at 17:33

0 Answers0