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.
If you didn't need to use interfaces, you could get by using concrete types:
Which might be better anyway, since interfaces could have required method implementations on them that any sort of proxying wouldn't handle very well (though, I think Castle has a method interceptor of some sort). Concrete types get rid of any sort of assumption there; the only real requirement is new().
Update:
Here's a sample creating the type from a string name, and also showing an invalid type: