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 only way I could think of the way to do it is to have an Init method on the interface.
interface IMyIntf {
void Initialize(string runTimeParam);
string RunTimeParam { get; }
}
Then to use it (in Unity) I would do this:
var IMyIntf = unityContainer.Resolve<IMyIntf>();
IMyIntf.Initialize("somevalue");
In this scenario runTimeParam
param is determined at run-time based on user input. The trivial case here simply returns the value of runTimeParam
but in reality the parameter will be something like file name and initialize method will do something with the file.
This creates a number of issues, namely that the Initialize
method is available on the interface and can be called multiple times. Setting a flag in the implementation and throwing exception on repeated call to Initialize
seems way clunky.
At the point where I resolve my interface I don't want to know anything about the implementation of IMyIntf
. What I do want, though, is the knowledge that this interface needs certain one time initialization parameters. Is there a way to somehow annotate(attributes?) the interface with this information and pass those to framework when the object is created?
Edit: Described the interface a bit more.
runTimeParam
is a dependency that is determined at run-time based on a user input. Should the alternative for this be splitting it into two interfaces - one for initialization and another for storing values? – Igor Zevaka