如何使用简单注入器解决具有值类型依赖性的 MVC 控制器?
How to resolve a MVC controller having a value type dependency with Simple Injector?
我有以下控制器:
public class MyController : Controller {
private readonly IService service;
private readonly int intDependency;
public MyController(IService service, int intDependency) {
this.service = service;
this.intDependency = intDependency;
}
...
}
显然解析不起作用,我也不能使用委托提供构造函数参数,因为这最终会导致多个构造函数注册。
在这种情况下正确的处理方法是什么?将值类型作为依赖注入通常是不正确的吗?将依赖项包装在接口后面会是更好的做法吗?
Is it generally uncorrect injecting value type as a dependency?
确实,如您所见,注入器无法知道它必须注入哪个 int
。真的没有意义。
Would it be a better practice to wrap the dependency behind an interface?
是的。
What is the correct way to proceed in this case?
你说的。接口或 class.
示例:
public class MyConfig
{
public int MyInt {get; set;}
}
您可以像这样配置 SimpleInjector:
container.RegisterSingleton(new MyConfig { MyInt = 42 });
您的控制器将是:
public MyController(IService service, MyConfig config) { ...
注意:有一种注入原始类型的方法:Primitive Dependencies with Simple Injector
但是,像我的示例一样,将基元包装在 class 中会更简单、更清晰。
Would it be a better practice to wrap the dependency behind an interface?
是的,这将是建议的解决方案。不支持值类型。不要直接注入值,而是将其包装在 class 中并注入它。
将接口放在实现之上的最佳做法,但这本身并不是必需的。简单的注入器无关紧要。所以这会起作用:
public class Values
{
public Values(int value)
{
this.SomeValue = value;
}
public int SomeValue { get; }
}
// Register as
container.RegisterSingleton<Values>(() => new Values(1));
有一些选择,虽然有点丑陋而且 IMO 不是要走的路。这些描述 here
我有以下控制器:
public class MyController : Controller {
private readonly IService service;
private readonly int intDependency;
public MyController(IService service, int intDependency) {
this.service = service;
this.intDependency = intDependency;
}
...
}
显然解析不起作用,我也不能使用委托提供构造函数参数,因为这最终会导致多个构造函数注册。
在这种情况下正确的处理方法是什么?将值类型作为依赖注入通常是不正确的吗?将依赖项包装在接口后面会是更好的做法吗?
Is it generally uncorrect injecting value type as a dependency?
确实,如您所见,注入器无法知道它必须注入哪个 int
。真的没有意义。
Would it be a better practice to wrap the dependency behind an interface?
是的。
What is the correct way to proceed in this case?
你说的。接口或 class.
示例:
public class MyConfig
{
public int MyInt {get; set;}
}
您可以像这样配置 SimpleInjector:
container.RegisterSingleton(new MyConfig { MyInt = 42 });
您的控制器将是:
public MyController(IService service, MyConfig config) { ...
注意:有一种注入原始类型的方法:Primitive Dependencies with Simple Injector 但是,像我的示例一样,将基元包装在 class 中会更简单、更清晰。
Would it be a better practice to wrap the dependency behind an interface?
是的,这将是建议的解决方案。不支持值类型。不要直接注入值,而是将其包装在 class 中并注入它。
将接口放在实现之上的最佳做法,但这本身并不是必需的。简单的注入器无关紧要。所以这会起作用:
public class Values
{
public Values(int value)
{
this.SomeValue = value;
}
public int SomeValue { get; }
}
// Register as
container.RegisterSingleton<Values>(() => new Values(1));
有一些选择,虽然有点丑陋而且 IMO 不是要走的路。这些描述 here