dependency injection - Different ways to inject dependencies in ASP.NET MVC Controllers? -
In most of the samples I've seen on the Web, DI is done in MVC controllers like this
< Code> Public Product Controller (IProductRepository Rep) {this._rep = RIP; }
A custom Controller Faititer is used and it uses the structure of the choice and the repository is injected.
Above the top
ex> Public Procure Controller () {this._rep = ObjectFactory.GetInstance & lt; IProductRepository & gt; (); }
This will get the same result, but the custom controller factory is not required.
As far as the test is concerned, the test app can have a different bootstrap, in such a way that when controllers are being tested they can get fake treasures and if used for real They will get real people
First of all, the service locator hides dependency. In its second example, seeing the public interface alone, it There is no way to know that the product controller
needs a repository.
What's more, I think I'll have to meet it.
IProductRepository repository = Mockery Pneumoc & lt; IProductRepository & gt; (); IProductController Controller = New ProductController (repository);
is obvious from
ObjectFactory.SetFactory (IProductRepository, New MockRepositoryFactory ()) IProductController Controller = New ProductController ();
Specifically if the ObjectFactory is configured in a test stability in the Setup
method.
Finally, the service locator pattern is sub optimal in display at least one special case: I bet you will be consuming people who apply for your outside control. That people generally prefer manufacturer injection (or one of the other DI methods) because it applies to each scenario why not use the method covering all cases ?
(Martin Fowler, in particular, offers a more thorough analysis in the "Service Locator vs Dependent Injection" section).
Comments
Post a Comment