ASP. NET MVC tutorial on how to use Ninject

  • 2021-10-27 07:06:51
  • OfStack

Why use Ninject?

Many other types of IOC containers rely too much on configuration files, always feel a little uncomfortable when they are configured, and use assembly-qualified names (that is, the full name of the type) to define them. If you don't pay attention, the whole program will collapse due to typos. Ninject is a lightning fast, ultra-lightweight IOC container based on. Net platform, which is mainly used to solve the coupling problem of modules in programs, and its purpose is to achieve minimum configuration. So if you don't like configuration and the heavyweight IOC framework, then use the small Apple Ninject!

The Ninject is a lightning fast, lightweight. . . . . Dependency injection framework, uh, uh, seems to be rarely used. Ninject is an DI container, which is used to decouple the components in ASP. NET MVC programs. When it comes to decoupling, there are actually other ways to achieve this purpose, such as interfaces


public interface ITest
{
 Decimal ValueProducts(IEnumerable<Product>products) ;
}
public class Test:ITest
{
 public Decimal ValueProducts(IEnumerable<Product>products) 
 {
 return products.sum(p=>p.Price);
 }
}
public class ShoppingCart
{
 private ITest test;
 public IEnumerable<Product>products{set;get;}
 public ShoppingCart( ITest test)
 {
 this.test=test;
 }
 public Decimal result(products);
}

Through the interface, we can say that we have achieved the desired result, that is, the coupling between Shopping and Test. But you can't do this in a controller


public ActionResult Index(){
 ITest IT=new Test();
 ShoppingCart cart=new ShoppingCart(IT);{Products=products};
 Decimal total=IT.result();
 return View(total);
}

We can only use Ninject to help us achieve it

You can download Ninect through nuget or download it through Ninject

So how can we use Ninject to help us solve the above problems?

In fact, it is not difficult to use Ninect. There are 3 steps in 1:


// In-controller 
public ActionResult Index()
{
 1: Create 1 A Ninject Kernel of 
 IKernel ninject=new StandardKernel();
 2: Is configuration Ninject Kernel , In fact, the implementation class and interface class are bound in the 1 Rise 
 ninject.Bind<ITest>().To<Test>();
 3: Finally 1 Step is to use Ninject Create 1 Objects 
 ITest IT=ninject.Get<ITest>();
}

From creating kernel to creating objects, it is very similar to Spring. Net.

Maybe a little bit obsessive-compulsive disorder, think so a lump of things put there is an eyesore, it is impossible for me to write this lump of things in every 1 action, of course not.

Let's create a dependency resolver (it seems to be very high, but it is actually encapsulating the above code)


public class NinjectResolver:IDependencyResolver
{
 private IKernel kernel;
 public NinjectResolver(IKernel kernel)
 {
 this.kernel=kernel; 
 AddBinding();
 }
 public IEnumerable<Object> GetServices(Type serviceType)
 {
 return kernel.GetAll(serviceType);
 }
 public Object GetService(Type serviceType)
 {
 return kernel.TryGet(serviceType);
 } 
 void AddBinding()
 {
 kernel.Bind<ITest>().To<Test>();
 }
}

IDependencyResolver This is System. Mvc Inheritance This interface must implement GetServices and GetService, AddBinding This method is used to bind implementation classes and interfaces

TryGet in GetService method is similar to Get above. When there is no proper binding, this will return 1 null value without throwing an exception, while GetAll in GetServices method can use this when binding multiple types of single 1

The last step is to find the file NinjectWebCommon. cs in the folder App_Start and then find RegisterServices (IKernel kernel) System.Web.Mvc.DependencyResolver.SetResolver(newNinjectResolver(kernel));

At this time, we modify the code in the controller


private ITest test;
public HomeController(ITest test)
{
 this.test=test;
}
public ActionResult Index(){
 ShoppingCart cart=new ShoppingCart(IT);{Products=products};
 Decimal total=IT.result(); return View(total);
}

The usage of Ninject is almost the same, and the following is a novel thing of Ninject
Is to specify attributes or constructor value, in fact, nothing, just the use of WithConstructorArgument and WithPropertyValue


public interface IHelper
 {
 Decimal ApplyDiscount(Decimal totalParam); 
 }
 public class Helper : IHelper
 {
 public Decimal DiscountSize { set; get; } 
 
 public decimal ApplyDiscount(decimal totalParam)
 {
 return (totalParam - (discountparam / 100m * totalParam));
 }
 }

private void AddBindings()
 {
 kernel.Bind<ITest>().To<Test>();
 
 kernel.Bind<IHelper>().To<Helper>().WithPropertyValue("DiscountSize", 50M); kernel.Bind<IHelper>().To<Helper>().WithConstructorArgument("discountparam", 50M);
 }

WithPropertyValue This has two parameters: 1 is the attribute name and 1 is the attribute value. This way, you can assign the default value to this attribute at the beginning of 1. Personally, the effect is not big, and there are other methods to achieve the same effect

WithConstructorArgument This is similar. Parameter 1 is the formal parameter of the constructor, and the following parameter is the value

Ok, Ninject is introduced here. If there is anything wrong, please forgive me.

Summarize


Related articles: