Basically what I want lies somewhere between FormatterServices.GetUninitializedObject() and Activator.CreateInstance().
This is for a plugin type of system so the type is variable, but I dont imagine that is an issue as both the above handle variable types just fine.
Basically I want to create an instance of the plugin's class, initialize all the fields and properties with their defined values but hold off on calling the constructor until my parent application sees if it has any configured settings it wants to inject in.
IInputDeviceEnumerator newEnum = (IInputDeviceEnumerator)FormatterServices.GetUninitializedObject(type);
if (newEnum is IIMConfigurable typeSettings)
{
string pluginDirectory = Path.GetDirectoryName(new System.Uri(typeSettings.GetType().Assembly.CodeBase).AbsolutePath);
string pluginConfigPath = Path.Combine(pluginDirectory, "settings.json");
if (File.Exists(pluginConfigPath))
{
try
{
JsonConvert.PopulateObject(File.ReadAllText(pluginConfigPath), typeSettings.config);
}
catch { }
}
SharedProperties.Settings.pluginSettings.settingsGroups.Add(typeSettings.config);
}
var constructor = type.GetConstructor(Type.EmptyTypes);
constructor.Invoke(newEnum, null);
I have a feeling the answer lies somewhere in PopulateObjectMembers, but I have not found enough info on it yet to decide.
As far as I know there are no analogues to C++'s placement new that combined with
FormatterServices.GetUninitializedObjectwould have probably solved your problem.But I believe that you are trying to do is a step in a wrong direction - trying to fight constructor invariants/work on uninitialized objects is usually a bad idea.
Unless this is some already active and (relatively) widely used plugin system and you have no other choice, I'd recommend you to redesign it using one of the more standard and language/platform-independent approaches:
Dictionary/dynamic.IPluginFactory.Create.Initializemethod that accepts the sameDictionary/dynamicand initializes the plugin after it had been constructed.Personally, I would have gone with constructor accepting
Dictionary/dynamic.