I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time:
At the moment the
I think I solved it and it feels rather wholesome, so it must be half right :))
I split IMyIntf
into a "getter" and a "setter" interfaces. So:
interface IMyIntf {
string RunTimeParam { get; }
}
interface IMyIntfSetter {
void Initialize(string runTimeParam);
IMyIntf MyIntf {get; }
}
Then the implementation:
class MyIntfImpl : IMyIntf, IMyIntfSetter {
string _runTimeParam;
void Initialize(string runTimeParam) {
_runTimeParam = runTimeParam;
}
string RunTimeParam { get; }
IMyIntf MyIntf {get {return this;} }
}
//Unity configuration:
//Only the setter is mapped to the implementation.
container.RegisterType();
//To retrieve an instance of IMyIntf:
//1. create the setter
IMyIntfSetter setter = container.Resolve();
//2. Init it
setter.Initialize("someparam");
//3. Use the IMyIntf accessor
IMyIntf intf = setter.MyIntf;
IMyIntfSetter.Initialize()
can still be called multiple times but using bits of Service Locator paradigm we can wrap it up quite nicely so that IMyIntfSetter
is almost an internal interface that is distinct from IMyIntf
.