问题
I want to resolve some dependencies which will only be known at runtime. I am using configuration file to configure Unity (not programmatically).
Here is some code to show what I want to achieve.
Classes:
internal class WorkflowFactory : IWorkflowFactory
{
public IItemWorkflow GetWorkflow(string discriminator)
{
// return an implementation of IItemWorkflow as specified in config file
return null;
}
}
public interface IWorkflowFactory
{
IItemWorkflow GetWorkflow(string discriminator);
}
public interface IItemWorkflow
{
void Handle(int id);
// More methods
}
Usage:
internal class Program
{
private static void Main(string[] args)
{
IWorkflowFactory factory = new WorkflowFactory();
// I am using args to show I do not know the string until runtime
var wf1 = factory.GetWorkflow(args[0]);
var wf2 = factory.GetWorkflow(args[1]);
}
}
If you know a better way, I am totally open and invite suggestions.
来源:https://stackoverflow.com/questions/43129606/unity-ioc-dynamic-resolution