Unity的多租户依赖解析

时间:2017-06-12 18:31:53

标签: c# unity-container ioc-container multi-tenant

考虑接口IWorkflow,是我们定义的SDK中的合同。租户可以提供自己的IWorkflow自定义实施。所以在运行时,我们需要根据租户上下文动态加载:

var container = new UnityContainer();
container.RegisterTenantCustomizations();
var workflow0 = container.ResolveForTenant<IWorkflow>("tenant0");
var workflow1 = container.ResolveForTenant<IWorkflow>("tenant1");
var workflow2 = container.ResolveForTenant<IWorkflow>("tenant2");
                          ^^^^^^^^^^^^^^^^  

这种扩展方法看起来像什么? Unity IOC是否提供了一个属性,我们可以使用它来为各自的租户装饰类?

1 个答案:

答案 0 :(得分:0)

假设您将组合根中的定义定义为

container.RegisterType<IWorkflow, TenantClassDefault>();
container.RegisterType<IWorkflow, TenantClass0>("tenant0");
container.RegisterType<IWorkflow, TenantClass1>("tenant1");
container.RegisterType<IWorkflow, TenantClass2>("tenant2");

然后你可以扩展IUnityContainer接口并像这样创建你的解析器

public static class IUnityContainerExt
{
    public static IWorkflow ResolveForTenant(this IUnityContainer container, string name)
    {
        IWorkflow workflow;
        try
        {
            workflow = container.Resolve<IWorkflow>(name); 
        }
        catch (ResolutionFailedException e)
        {
            //If the resolver can't resolve the name it will throw ResolutionFailedException and you can select the default instead
            workflow = container.Resolve<IWorkflow>();
        }
        return workflow;
    }
}

然后你可以直接在容器上使用它

var workflow0 = container.ResolveForTenant("tenant1");

您可以阅读更多相关信息here