C
C#3y ago
Thinker

Creating an instance of a class using DI [Answered]

This is purely just out of curiosity. If you have a class which takes some arguments in its ctor and you want to create an instance of the class using some types registered in DI, is there any simple way to do that?
13 Replies
Pobiega
Pobiega3y ago
Is the class you are wanting to create also registered? like, you want to create a class A instance, and has a ctor like A(B b, C c)
Thinker
ThinkerOP3y ago
B and C are registered in DI and I want to create an instance of A using the registered types.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Thinker
ThinkerOP3y ago
Of course I could just get the B and C from DI and create it manually, but I was just wondering if there was some automatic way.
Pobiega
Pobiega3y ago
if A is not registered, you just get B and C out but ideally, A would be regged is A registered or not?
Thinker
ThinkerOP3y ago
Again this is just a hypothetical so doesn't really matter, sure it could be.
Pobiega
Pobiega3y ago
if it is, you just resolve A directly and the DI container will internally resolve B and C for you
Thinker
ThinkerOP3y ago
Right Was probably just wondering if there was a way to resolve A without registering it.
Pobiega
Pobiega3y ago
like, you'd do something along the lines of... serviceProvider.Resolve<A>(); and it would look at A and see if it could resolve all the dependencies and in that case do so? afaik, not possible and also a bit against the philosophy of IOC containers
Thinker
ThinkerOP3y ago
huh well thanks
Thinker
ThinkerOP3y ago
Instantiate a type with constructor arguments provided directly and/or from an IServiceProvider.
That's literally the definition of what I was looking for. Thanks.
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?