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
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)
B
and C
are registered in DI and I want to create an instance of A
using the registered types.Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
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.
if A is not registered, you just get B and C out
but ideally, A would be regged
is
A
registered or not?Again this is just a hypothetical so doesn't really matter, sure it could be.
if it is, you just resolve A directly
and the DI container will internally resolve B and C for you
Right
Was probably just wondering if there was a way to resolve A without registering it.
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 containershuh
well thanks
There's https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.activatorutilities?view=dotnet-plat-ext-6.0
Example usage https://github.com/dotnet/runtime/blob/0bce5f69ee027fd148a8d878af5642726ad36a19/src/libraries/Microsoft.Extensions.Http/src/DefaultTypedHttpClientFactory.cs#L36
ActivatorUtilities Class (Microsoft.Extensions.DependencyInjection)
Helper code for the various activator services.
GitHub
runtime/DefaultTypedHttpClientFactory.cs at 0bce5f69ee027fd148a8d87...
.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps. - runtime/DefaultTypedHttpClientFactory.cs at 0bce5f69ee027fd148a8d878af5642726ad36a19 · dotnet/runtime
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.
✅ This post has been marked as answered!