如果在Unity

时间:2015-10-13 09:39:42

标签: c# unity-container

我有以下容器

IUnityContainer container = new UnityContainer();
container.RegisterType<IFoo, FooOne>("One");
container.RegisterType<IFoo, FooTwo>("Two");
container.RegisterType<IFoo, FooThree>("Three");
container.RegisterType<IFoo, FooFour>("Four");
container.RegisterType<IFoo, FooFive>("Five");
container.RegisterType<IFoo, FooSix>("Six");

现在当我访问它时,我使用

IFoo foo = container.Resolve<IFoo>(AliasString);

现在问题是我从User获取Alias字符串,并且如果Alias不在注册者中,则希望返回FooOne,例如 如果Alias传递为“SEVEN”,那么它应该返回FooOne

有没有办法实现它?

注意:我不希望在容器注册人上有一个循环......

请帮助

1 个答案:

答案 0 :(得分:1)

使用容器的IsRegistered方法:

IFoo foo;
if (Container.IsRegistered<IFoo>(AliasString))
{
    foo = container.Resolve<IFoo>(AliasString);
}
else
{
    foo = container.Resolve<IFoo>("One");
}

要排除循环检查,您可以将其包装到某个工厂:

public class Factory
{
    private readonly IUnityContainer _container;
    private readonly HashSet<string> _classes = new HashSet<string>();

    public Factory(IUnityContainer container)
    {
        _container = container;
    }
    public void Register<TInterface, TClass>(string alias) where TClass : TInterface
    {
        _classes.Add(alias);
        _container.RegisterType<TInterface, TClass>(alias);
    }
    public TInterface Resolve<TInterface>(string alias)
    {
        if (_classes.Contains(alias))
            return _container.Resolve<TInterface>(alias);
        return _container.Resolve<TInterface>("default");
    }
}

var factory = new Factory(container);
factory.Register<IFoo, FooOne>("One");
IFoo foo = factory.Resolve<IFoo>(AliasString);