Hey
I'm currently attempting to read information about an object from the web.config file and create and object based on that. However, I only wish to be able to create objects from classes that extend a particular interface (IModule
). The type of the object is coming from a type attribute in the web.config:
<module moduleAlias="Test" type="ASPNETMVCMODULES.TestModule" connectionStringName="ApplicationServices">
<properties>
<property name="prop1" value="abc" type="System.String"/>
<property name="prop2" value="123" type="System.Int32"/>
</properties>
</module>
In my code, ASPNETMVCMODULES.TestModule
does, in fact, extend IModule
and it loads in just fine with the code below:
The problem I am having is that, because I'm defining every object as an IModule
, I cannot gain access to any additional methods or properties I add to the extending class. Is there any way for me to create the object with its own type, whilst ensuring it extends IModule
? Might using System.Convert
be worthwhile to convert from IModule
to TestModule
(in this case)?
Ideally, I'd like to be able to define the object using modT
which is type of the object straight from the web.config.
public void LoadModules()
{
ASPNETMVCMODULES.Configuration.ModulesSection allModules = (ASPNETMVCMODULES.Configuration.ModulesSection)System.Web.Configuration.WebConfigurationManager.GetSection("mvcmodules");
foreach (Configuration.Module mod in allModules.Modules)
{
Type modT = Type.GetType(mod.ModuleType);
IModule ob = (IModule)Activator.CreateInstance(modT);
foreach (ASPNETMVCMODULES.Configuration.ModuleProperty modP in mod.ModuleProperties)
{
object origVal = modP.Value;
object newVal = Convert.ChangeType(origVal, Type.GetType(modP.PropertyTypeString));
ob.Properties.Add(modP.Name, newVal);
}
//Have to add some properties manually
ob.Properties.Add("ConnectionString", (string)mod.ConnectionString);
//RegisterModule(string, IModule)
RegisterModule(mod.ModuleAlias, ob);
}
}
Thanks