I do not fully understand the meaning of using DI (for example autofac ). Perhaps I do not correctly interpret its meaning because of the wrong scope.

The context of the task is the following: it is necessary to implement the autofac module in the testing system. Actually the problem is, why should I write code with dependency resolution through the same autofac if I can explicitly create objects and transfer them to the constructor.

For example, there is ApiController , he has a bunch of arguments in the constructor, such as user context, registration manager, manager for sending SMS, etc. All these objects, in turn, are also quite difficult to initialize. For example:

Option with Autofac

ISomeClassInterface someClass; var builder = new ContainerBuilder(); builder.RegisterType<SomeService>(); var container = builder.Build(); someClass = new SomeClass(container.Resolve<SomeService>(); 

Option without Autofac

 ISomeClassInterface someClass; ISomeService service = new SomeService(some arguments...); someClass = new SomeClass(service); 
  • It seems to me that you did not understand what the advantage of DI is because in your example you still pass your SomeService as an argument in the constructor of the class SomeClass . And I understand that your container.Resolve should return SomeClass - koks_rs

1 answer 1

You yourself answered your question: "All these objects, in turn, are also quite difficult to initialize." The more complicated, the easier it is to make a mistake. Of course, you can not use any DI. But, first, DI simplifies the initialization of objects. Secondly, DI simplifies the substitution of objects. For example, you will want to use another registration manager. Without DI, you will have to change the code in several places, with DI - in one.

Compare:

 A a = new A(new B(new C()), new D(new E())...); 

And somehow conditionally

 A a = container.Resolve<A>(); 
  • But in this case, DI will create some kind of dummy parameters and pass them to the constructor, or am I mistaken? If not, then you can fasten it in your first example, and some kind of mock'er. - QuaternioNoir
  • The moment, if I have several projects in the solution, some of them will be guaranteed to be launched when executing tests. Is it possible to initialize objects with an object already created in any project? For example, changing the Core creates a registration manager, so here, is it possible to pass a link to this object in apiController? - QuaternioNoir
  • It "kills" only those types that were previously registered in the container. I agree, you can do without DI in the unit test itself. - RusArt
  • I think you can, you need to watch the documentation of a separate DI. - RusArt