Unity - 如何手动创建具有依赖关系的控制器?

时间:2016-12-21 10:32:55

标签: c# asp.net-mvc dependency-injection controller unity-container

我正在尝试手动创建控制器实例,但它有一些依赖关系,现在我只是自动解析所有这些并将它们传递给控制器​​构造函数

var c = new MyController(container.Resolve<IInterface1>(),
                         container.Resolve<IInterface2>())

是否可以通过Unity创建控制器实例以自动解决所有依赖项?

1 个答案:

答案 0 :(得分:1)

您可以使用InjectionConstructor对其进行归档。例如:

container.RegisterType<IInterface1, Implementation1>();
container.RegisterType<IInterface2, Implementation2>();

container.RegisterType<MyController>(new InjectionConstructor(
    container.Resolve<IInterface1>(), 
    container.Resolve<IInterface2>()));

然后将此方法与ControllerFactory结合使用。

相关问题