Unity IoC dynamic resolution

余生长醉 提交于 2019-12-25 09:43:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!