How to organize the use of DI Framework in the application?

EDIT: I forgot to move the kernel to the parent class without generation and provide a virtual method to access it. I understand that the example below, as is, would create many instances of the kernel.

I just found out how to give an injection last week, and here is how I set up now:

using Ninject; using System.Reflection; namespace Infrastructure { public static class Inject<T> { static bool b = Bootstrap(); static IKernel kernel; static bool Bootstrap() { kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); return true; } public static T New() { return kernel.Get<T>(); } } } 

And then I plan to make the various ninject module classes part of the Infrastructure namespace to load them.

I have not been able to find anything here or Google that provides examples of how to actually organize the use of Ninject in your project, but this seems right to me, as it allows me to use only the Ninject link in this assembly. Is this more or less the β€œright” way or is there a better design?

+1
source share
1 answer

There are several problems with how you are doing now.

Let me start with the obvious C # problem first: Static class variables in common classes are allocated based on T In other words, Inject<IUserRepository> and Inject<IOrderRepository> will have their own IKernel instance, which is unlikely what you really want, since most likely you will need one IKernel for the life of your application. If you have no IKernel for the application, there is no way to register types as singleton, since singleton always has scope at the container level, and not at the application level. So, it's better to rewrite the class as universal and transfer the generic type argument to the method:

 Inject.New<T>() 
The second problem is dependency injection. It seems to me that you are trying to use Anti-Virus in Locator, since you are probably explicitly calling Inject.New<T> from your application. The DI container should only be indicated on the application launch path and should be able to build a complete graphical object of related objects. Thus, you can ask the container to get a root level object for you (for example, Controller in the context of MVC), and the rest of the application will not pay attention to the use of any DI technology. When you do this, there is no need to abstract the use of the container (as it was with your Inject class).

Not all applications or user interface technologies allow this BTW. I try to hide my container (how you do it) when working with the Web Forms application, because it is not possible to correctly inject dependencies in the Page , IHttpHandler and UserControl classes.

+4
source

Source: https://habr.com/ru/post/1397556/


All Articles