[英]Unity dependency injection for Models
I've just started using Unity with MVC and I'm running into, what I see as, a bit of code duplication. 我刚刚开始将Unity与MVC结合使用,并且遇到了一些代码重复的问题。 Consider the following Controller/Model pattern:
考虑以下控制器/模型模式:
Controller: 控制器:
public class MyController : Controller {
private readonly IDependency1 _dependency1;
private readonly IDependency2 _dependency2;
private readonly IDependency3 _dependency3;
public MyController(
IDependency1 dependency1,
IDependency2 dependency2,
IDependency3 dependency3
) {
}
public ActionResult Thingy() {
var model = new Thingy(_dependency1, _dependency2, _dependency3);
model.DoLogic();
model.SetUpView();
model.Finalize();
return View(model);
}
}
Model: 模型:
public class Thingy {
private readonly IDependency1 _dependency1;
private readonly IDependency2 _dependency2;
private readonly IDependency3 _dependency3;
public Thingy(
IDependency1 dependency1,
IDependency2 dependency2,
IDependency3 dependency3
) {
}
// Now I can use my dependencies
}
This allows me to implement skinny controllers/fat models, however I am now duplicating dependencies in both Controller & Model. 这使我可以实现瘦控制器/胖模型,但是现在我在控制器和模型中都复制了依赖项。
I saw that I can use attributes in my model: 我看到可以在模型中使用属性:
public class Thingy {
[Dependency]
public IDependency1 Dependency1 { private get; set; };
[Dependency]
public IDependency2 Dependency2 { private get; set; };
[Dependency]
public IDependency3 Dependency3 { private get; set; };
}
Then initialize my model in my action like so: 然后像这样初始化我的模型:
public ActionResult Thingy() {
// No need to pass in via constructor
var model = DependencyResolver.Current.GetService<Thingy>();
}
Nice & lean from a coding POV, but I read that this is an anti-pattern? 从编码POV来看很不错,但是我读到这是反模式吗?
Q: Why is this considered an anti-pattern and can I modify my structure to prevent code duplication? 问:为什么将其视为反模式,我可以修改结构以防止代码重复吗?
Yes, this is anti-pattern. 是的,这是反模式。 One reason - excess relatedness code.
原因之一-过多的关联性代码。 If you want to replace IoC container (for example the NInject) then you have to change the code of the controller and model.
如果要替换IoC容器(例如NInject),则必须更改控制器和模型的代码。 It violates Open/closed principle ( http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) ).
它违反了开放/封闭原则( http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) )。 Also, you will be hard to do unit testing controller.
另外,您将很难做单元测试控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.