统一流利的注册 - 这可以更短吗?

时间:2011-06-10 09:50:43

标签: unity-container

如果我有一个接受几个构造函数参数的类,包括一个可以为null的字符串,我目前正在使用以下语法进行注册:

    container.RegisterType<ISomething, Something>(
new InjectionConstructor(new InjectionParameter<string>(aString), typeof(ISomethingHelper), typeof(ISomethingManager)))

我添加了InjectionParameter来处理一个null aString的情况,Unity没有这个抱怨。

这一切是必要的还是我可以缩短一点?

1 个答案:

答案 0 :(得分:0)

Null是一种特殊情况,因为我们无法从null类型的常量派生类型(它只是通过编译器作为类型对象)。没有写一个小帮助函数/类,是的,它就像它一样短。

我可以看到写这样的东西:

public static class NullParam
{
    public InjectionParameter OfType<T>()
        where T : class
    {
        return new InjectionParameter<T>(null);
    }
}

然后你可以把上面写成:

container.RegisterType<ISomething, Something>(
    new InjectionConstructor(
        NullParam.OfType<string>, typeof(ISomethingHelper), typeof(ISomethingManager)));

我不确定它是否足够短,值得引入助手。

Unity API围绕规则性和可扩展性而设计,而不是简洁或方便。这确实使一些事物比理想的更有意义。好处是,编写小包装器和帮助器非常容易,使注册代码看起来像你想要的那样。