C
C#•2y ago
Jason

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
chef drone builder
chef drone builder•2y ago
This is not valid c# syntax. I would recommend to look into how the activatorutilities.createinstance method works 🙂
chef drone builder
chef drone builder•2y ago
chef drone builder
chef drone builder•2y ago
wait, let me give an example
undisputed world champions
can't you just ActivatorUtilities.CreateInstance<CxvParser>(host.Services) to let DI resolve the ctor parameters?
Jason
Jason•2y ago
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
Jason
Jason•2y ago
@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.
undisputed world champions
those services are registered as scoped have your tried creating a scope and using the scopes serviceprovider instead?
chef drone builder
chef drone builder•2y ago
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.
undisputed world champions
(should say so in the actual error message to 😉 )
Jason
Jason•2y ago
I'm trying it out now, thanks. I didn't see anything about scoping in the error but I'll look again
Jason
Jason•2y ago
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?
undisputed world champions
the squiggly lines make me suspect you are missing a await there 😉 what does it say there?
Jason
Jason•2y ago
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
undisputed world champions
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 awaited 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)