I'm trying to register dynamic implementations for interfaces that will be injected into objects created by my IoC container (Unity in this case).
Here is the high-level approach I'm taking:
- Dynamically load a list of properties from a JSON file. I'm using JSON.NET for this currently.
- Map that dynamic object to an interface. I'm currently using Impromptu for this.
- Register that dynamic object with my IoC container for the interface type
Here is the code that should "theoretically" work:
var configJson = File.ReadAllText(".\\Configuration\\DataCollector.json");
dynamic expando = JsonConvert.DeserializeObject(configJson);
var container = new UnityContainer();
var interfaceType = Type.GetType("Manufacturing.Framework.Configuration.IDataCollectorConfiguration", true);
var interfaceInstance = Impromptu.ActLike(expando, interfaceType);
container.RegisterInstance(interfaceType, "IDataCollectorConfiguration", interfaceInstance, new ContainerControlledLifetimeManager());
All is well until the last line. Unity doesn't like the fact that I'm not giving it an actual interface instance, just a duck typed instance.
The type ImpromptuInterface.ActLikeCaster cannot be assigned to variables of type Manufacturing.Framework.Configuration.IDataCollectorConfiguration
Why am I doing this? I'm trying to simplify my complex application configuration by storing my settings as JSON, defining interfaces to map to that JSON, and then have my IoC container automatically inject the proper configuration into any class that asks for it.