ActivatorUtilities.CreateInstance of a class instantiated within Program.cs 'unable to resolve type'
I can verify that the two services the class takes in the constructor are correctly registered. I'm not sure why I'm not able to call the 'Parse()' method from the class here.
14 Replies
This is not valid c# syntax. I would recommend to look into how the activatorutilities.createinstance method works 🙂
wait, let me give an example
can't you just
ActivatorUtilities.CreateInstance<CxvParser>(host.Services)
to let DI resolve the ctor parameters?I tried that method, using host.Services, and I still got the error, so I tried explicitly naming the services and that's what you see above
@kocha I did reference the docs before posting and I know the content within the parameter is meant for any additional services outside of those registered, but that was before realizing 'host.Services' wouldn't work.
those services are registered as scoped
have your tried creating a scope and using the scopes serviceprovider instead?
yes, I see, what i meant is, that you cant just pass types as parameters into a method, you would need typeof(IDataContext). But this doesn't really matter, as that is not how the method works.
(should say so in the actual error message to 😉 )
I'm trying it out now, thanks. I didn't see anything about scoping in the error but I'll look again
It would appear that one of the two services needed another service that wasn't registered. After correcting for this, the error goes away which is great, however the instance of this class 'CsvParser' is not being called! So the method 'Parse()' isn't being activated now. I'm lost. Is this a scope thing again?
the squiggly lines make me suspect you are missing a
await
there 😉
what does it say there?Why did that work. I knew about the lack of async but left it as is because, long story short, the parsing method is making use of two services, one of of which is async, the other not. So I was just Task.FromResult()ing that
you have to read up on async/await sometime, but long story short: async methods initially only run to the first
await
and return a Task
that has to be await
ed itself to finish the rest of the async function
you say you didn't even use a async function, so tbh i'm not sure what would happen then
it's best practice to just use async/await all the way up to the main method (don't do AsyncFunction().Result
or AsyncFunction().Wait()
yourself, do await AsyncFunction()
instead)