❔ Question on how AddDbContext works
I have some beginner question. I'm confused about how
works.
Later in the guide, they have
Which has
Online_WriterContext db
as the input. How does the program know the correct configuration db
is supposed to be if db
is a fresh new instance of Online_WriterContext
. How do these two code segments connect to each other?5 Replies
Assuming that db is a fresh new instance of the
Online_WriterContext
, how does db.SaveChangesAsync()
know to do the correct thing
Here is my Online_WriterContext class, but I don't see how the configuration is inbuilt into the class
cracks knuckles
I don't see how the configuration is inbuilt into the classit's not, it's passed in, via
options
How does the program know the correct configuration db is supposed to be if db is a fresh new instance of Online_WriterContextit's passed in via
options
How do these two code segments connect to each other?
.AddDbContext<Online_WriterContext>()
registers the Online_WriterContext
class with your application's IoC container
as well as all of its dependencies
(which in this case just consists of DbContextOptions<Online_WriteContext>
)
or
probably more specifically
it registers Online_WriterContext
with custom construction logic that uses a DbContextFactory
to construct instances
and all of the dependencies of DbContextFactory
which includes classes that store configuration/options information
configuration/options information that is built within your optionsBuilder
delegate that you passed to AddDbContext()
so, when you register endpoints with the application, and define Online_WriterContext
as a dependency for that endpoint
it's the IoC container that resolves that dependency
because .AddDbContext()
told it how to do so
based on the configuration you provided to .AddDbContext()
What is IoC short for?
The rest of the explanation is great and I think I understand the gist of it. Thank you!
Inversion of Control
whereby you don't create and manage object lifetimes yourself
you "invert" that control, and hand it over to someone else
the IoC Container
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.