c# - Unity dependency injection for Models -
I have just started using unity with MVC and I am running in, what I see, code A bit of duplication Consider the following controller / model pattern:
Controller:
Public class MyController: Controller {Private Readonly ID Freedom 1 _ Dependency 1; Private Read Only Freedom 2 _ Dependence 2; Private only read independence 3 _ dependency 3; Public MyController (Independence 1 Dependency 1, Hospitality Dependency 2, Freedom Dependency 3) {} Public Activity Result () {var model = New Thingi (_ dependency 1, _ dependency 2, _ dependency 3); Model.DoLogic (); Model.SetUpView (); Model.Finalize (); See Return (Model); }} Model:
Public class Thingi {Private Readonly ID Freedom 1 _ dependency 1; Private Read Only Freedom 2 _ Dependence 2; Private only read independence 3 _ dependency 3; This allows me to implement a thin controller / fat model, although now I am doubling dependencies in both controllers; Model
I noticed that I can use the attributes in my model:
public class Thing {[dependence] Public Official Freedom 1 Dependency 1 {Received Private; Set; }; [Dependency] Public Official Dependence 2 Dependencies 2 {Received Private; Set; }; [Dependence] Public dependency 3 Dependence 3 Received personal; Set; }; } Then initialize my functioning like my action:
Public Action Result Thingi () {// Anyone to pass through Constructor Do not need var model = DependencyResolver.Current.GetService & LT; Thingy & gt; (); } Good & amp; Coding is lean from POV, but I have read that this is an anti-pattern?
Q: Why is this considered an anti-pattern and can I modify my structure to prevent code repeat?
Yes, this anti-pattern is one reason - additional related code if you are an IOC container (For example, NINJject), you have to change the code of the controller and the model it violates open / closed principle () Also, you will be difficult to do the unit test controller.
Comments
Post a Comment