I am attempting to implement some generic config types and have bumped into an issue with conversions. Ideally what I'd like is a strongly typed instance of configuration values that can be assigned to our different Exporters.
What I have is:
IConfigurableExport
: Interface to mark exporter as configurable and contains aICollection<IExportConfiguration<Object>> Configurations
propertyIExportConfiguration<T>
: Interface to define common properties (Name, Description, etc.)ExportConfiguration<T>
: Abstract class that implementsIExportConfiguration<T>
, sets the interface properties as Abstract, adds some common functionality like setting the value of itself from a list of configuration values and whatnotConfigurationInstance<bool>
: InheritsExporterConfiguration<Boolean>
The UI to configure the exporters is dynamically built based on the values from IConfigurableExport.Configurations. When I try to call IConfigurableExport.Configurations I get a casting error. Here is some sample code to illustrate the problem:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var t = new MyExporter();
var configs = t.Configurations;
foreach(var conf in configs){
Console.WriteLine(conf.Name);
}
}
}
public interface IExportConfiguration<T>{
string Description {get;}
Guid Id {get;}
string Name {get;}
T Value {get; set;}
}
public abstract class ExportConfiguration<T>
: IExportConfiguration<T>
{
public abstract string Description { get; }
public abstract string Name { get; }
public abstract Guid Id { get; }
public abstract T Value { get; set; }
public abstract T DefaultValue { get; set; }
public virtual void SetValue(ICollection<KeyValuePair<Guid, object>> values)
{
if (values.Any(kvp => kvp.Key == this.Id))
Value = (T)values.First(kvp => kvp.Key == this.Id).Value;
else
Value = this.DefaultValue == null ? this.DefaultValue : default(T);
}
}
public interface IConfigurableExport {
ICollection<IExportConfiguration<object>> Configurations {get;}
}
public class MyConfig : ExportConfiguration<bool> {
public override string Description { get { return "This is my description"; }}
public override string Name { get{ return "My Config Name"; }}
public override Guid Id { get { return Guid.Parse("b6a9b81d-412d-4aa8-9090-37c9deb1a9f4"); }}
public override bool Value { get; set;}
public override bool DefaultValue { get; set;}
}
public class MyExporter : IConfigurableExport {
MyConfig conf = new MyConfig();
public ICollection<IExportConfiguration<object>> Configurations {
get {
return new List<IExportConfiguration<object>> { (IExportConfiguration<object>)conf };
}
}
}
Here is a dontnetfiddle to illustrate the problem