c# - DI with Unity Container - 使用附加参数解析的最佳实践?

标签 c# .net unity-container

例子:

IApple 和实现 AppleApple 的构造函数:

public Apple(IVitamin vitamin, int size)

我可以注册所有的 DI 和 IApple:

container.RegisterType<IApple,Apple>();
container.RegisterInstance<IVitamin>(vitamin);

我现在可以在创建 apple 实例时覆盖参数以插入 int 大小参数:

var apple = container.Resolve<IApple>(new ParameterOverrides<Apple> {{"size", 9001}}

似乎很麻烦,你必须在那里写参数的字符串(“size”)。当涉及其他参数时,这是进行 DI 的首选方法吗?还是我必须创建一个 AppleFactory(或通常是一个工厂)来处理它? (必须为每个具有非 DI 属性和 DI 属性的类编写一个工厂似乎有点过分了。

或者您不应该手动覆盖和设置该属性?

var apple = container.Resolve<IApple>();
apple.Size = 9001;

这样代码逻辑将从构造函数转移到属性的 setter 。

最佳答案

It seems bothersome that you have to write the string of the parameter in there ("size")

是的,它很丑陋,但没有办法解决它,至少在 Unity 中没有。

It seems overkill to have to write a factory for every class that has non-DI properties as well as DI ones

是的,但这可能是您无论如何都应该做的。您的大部分代码不应直接依赖于容器。

如果你创建一个工厂,参数覆盖就不会那么难看,因为你可以使用 nameof 而不是字符串:

class AppleFactory : IAppleFactory
{
    ...

    public IApple CreateApple(int size)
    {
        return _container.Resolve<IApple>(new ParameterOverrides<Apple> {{nameof(size), size}};
    }
}

另一种方法是使用我的 Unity.Extras.AutoFactory扩展名,但请记住它处于 alpha 状态...

关于c# - DI with Unity Container - 使用附加参数解析的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889402/

相关文章:

c# - ListView 项目不清除 (C#/WPF)

asp.net-mvc-3 - controller 'TestController' 单个实例不能用于处理多个请求

silverlight - 如何获取unitycontainer的实例?

c# - 在 Unity 中注册用于拦截的实例

c# - 从后面的代码设置 UWP NavigationViewItem 图标

c# - 在哪里可以获得适用于 Windows 10 IoT 的 SOS?

c# - nHibernate 不在同一 session 中通过 Oracle 包更新其他表

c# - 我可以有一个不可变的 IEnumerable<> 吗?

c# - 如何根据 swift 方法将 C# 方法三重化

c# - DataGridView - 如何连接到与单元格更改关联的事件?