Stream: dotnet
Topic: creating resources.
Dennis Brox (Feb 27 2022 at 23:06):
I need to create resources at runtime. The following happens:
string n = "Hl7.Fhir.R4.Core";
string c = "Person";
var myObj = Activator.CreateInstance(n, c);
System.TypeLoadException
HResult=0x80131522
Message=Could not load type 'Person' from assembly 'Hl7.Fhir.R4.Core, Version=3.8.0.0, Culture=neutral, PublicKeyToken=d706911480550fc3'.
Is this a constructor problem or something I'm missing in C#. It has obviously found the dll correctly.
Brian Postlethwaite (Feb 28 2022 at 09:10):
To test things out, just create a new person normally (verifying that the assemblies are all loaded) then see if your code works...
Gino Canessa (Feb 28 2022 at 15:44):
Hi Dennis, there are some utilities in the Hl7.Fhir.Model.ModelInfo
class to make these types of operations easier:
string ft = "Person";
if (!Hl7.Fhir.Model.ModelInfo.FhirTypeToCsType.ContainsKey(ft))
{
throw new Exception($"{ft} is not a valid FHIR Type");
}
var typed = Activator.CreateInstance(Hl7.Fhir.Model.ModelInfo.FhirTypeToCsType[ft]);
Dennis Brox (Feb 28 2022 at 21:58):
Two nice FhirType functions but CreateInstance works C# normally doesn't work i.e. it creates a resource nicely, the class has values like a resource I create normally, GetType returns the same values. But there is no constructor i.e. I can't assign property values to it.
Gino Canessa (Feb 28 2022 at 22:06):
I am unclear on what you are trying to do. If you are asking about code-completion, yes a var
type from Activator.CreateInstance
will not know what you are doing.
If you know the type at compile-time, you can just use new Hl7.Fhir.Model.Person()
to create the instance.
Dennis Brox (Mar 01 2022 at 22:59):
I'm trying to create a FHIR class at runtime where all I know is the class name i.e. a string "Person" and assign it values when it is created. Why else would you use CreateInstance? I want to handle values in a dictionary in one line generically instead of using scads of cases in a switch statement. On another "Type" issue, how do convert Address.Line to some type I can use in C#? I created it as a string [] but I can't get it back as either an array or a list.
Brian Postlethwaite (Mar 02 2022 at 00:36):
When I do this I'm using the ClassMapping and PropertyMapping classes to manipulate things.
Otherwise you could just do regular dotnet reflection.
That's a pretty advanced part of the libs, and you'd want to understand what's going on internally to ensure that you know how things might break into the future.
Last updated: Apr 12 2022 at 19:14 UTC