IOC vs New Recommendations

I recently looked at some source code provided by community leaders on their open source implementations. One of these projects used the IOC. Here's an example of hypothetical code:

public class Class1
{
    private ISomeInterface _someObject;

    public Class1(ISomeInterface someObject)
    {
        _someObject = someObject;
    }

    // some more code and then

    var someOtherObject = new SomeOtherObject();
}

      

My question is not what is for the IOC and how to use them in technical terms, but what are the guidelines for creating objects. All this effort, and then this line uses the "new" operator. I don't quite understand. What object should IOC create and for which of them is it allowed to create a new operator?

+3


source to share


2 answers


Typically, if something provides a service that can be replaced either for testing or to use a different implementation (for example, for different authentication services), then inject the dependency. If it's something like a collection, or a simple data object that doesn't provide the behavior you would ever want to change, then it's fine to instantiate it inside a class.



+6


source


You usually use IoC

because:

  • Addiction that may change in the future
  • For code versus interfaces, not concrete types
  • To enable mockery of these dependencies in Unit Testing scripts


You can avoid using it IoC

in the event that you do not control the dependency, for example, StringBuilder

there will always be StringBuilder

and has a certain behavior, and you usually don't really need to mock it; while you might want to mock HttpRequestBase

it because it's an external dependency on having an internet connection, for example, which is a problem during unit tests (longer runtime and something out of your control).

The same happens for database access repositories, etc.

+5


source







All Articles