Is using GetAwaiter().GetResult() for async methods in constructor a hack!
So I am writing my datalayer for a database, however I want to use one instance of that database for all the read and write methods in my datalayer class.
In order for me to initialize the database, I need to use the "await" keyword because it's an async function.
I planned to initialize the database at the constructor of my base datalayer class.
but I can't use "await" in the constructor.
So I decided to use GetAwaiter().GetResult().
It works, but I don't see this often. So I don't think it's appropriate.
What do you think?
11 Replies
It is a hack, yes, and it is blocking
A better idea would be a private constructor and an factory method
Interesting, Thank you. I will use this
Why don't you use dependency injection instead of creating a new instance of your db class?
That way if you scope it to be a singleton, you can use it throughout your data layer and it'll keep that single instance of the database connection for you to use for read/write, executing stored procedures etc
This sounds more efficient. I will work on it
The way I usually do it is I'll create a DIConfig class that is called in a Startup.cs class I build (which gets called from Program.cs/Main.cs depending on your setup).
That allows me to keep things centralised in a way that's easy to understand.
https://positiwise.com/blog/dependency-injection-in-net-core-with-example This is an example of dependency injection but he does his dependency injection in his Program.cs rather than seperating it further and passing it down like I do
Parag Mehta
Positiwise
What is Dependency Injection in .NET Core? - Explained with Code Ex...
Explain dependency injection in .NET Core with code examples. Learn why DI is needed and steps to implement it in your .NET applications.
It gets you into a good habit of creating interfaces, thinking about inheritance and base classes etc. It helped me start framing things in a way of how can I build something so I can extend it in the future without creating tech debt whilst also avoiding duplicate code.
Assuming you use ASP, then yeah, DI comes built-in and is the preferred way of getting a
DbContext
injectedI have fixed it now
I used your method and the dependency injection method
That's awesome news! Glad you managed to pick it up so quickly π
It seemed logical, so I just decided to test it. Thank you very muchπ
We love logic π