依赖注入-Ninject 与Autofac 用法比较

1.分别安装Ninject  和 Autofac 并引用  

总结: 通过比较发现,两者用法基本相同,只是方法名称和调用方式不同,Ninject 用 new StandardKernel()方法获取IKernel对象,并通过该对象Bind() To 接口和实现类,通过该对象的Get()

方法获取接口对象。而Autofac则通过New ContianerBuilder()方法来获取一个注入容器实例,并用该实例的RegisterType() As  来建立接口和实现类的关系,通过该对象的Resolve()

来获取接口对象。两者实现步骤一致,方法不同而已!

 

install-package Ninject -version 3.0.1.10  

install-package Autofac

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EssentialTools.Models;
using Ninject;
using Autofac;
namespace EssentialTools.Controllers
{
public class HomeController : Controller
{
private Product[] products = {
new Product{ Name="Kayak",Category="Watersports",Price=275M},
new Product{ Name="Lifejacket",Category="Watersports",Price=48.95M},
new Product{ Name="Soccer ball",Category="Soccer",Price=19.50M},
new Product{ Name="Corner flag",Category="Soccer",Price=34.95M}
};
// GET: Home
public ActionResult Index()
{
//方法一:使用Ninject 依赖解析器实现依赖注入
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
IValueCalculator calc = ninjectKernel.Get<IValueCalculator>();
//方法二:使用Autofac 以来解析器实现依赖注入
var builder =new ContainerBuilder();
builder.RegisterType<LinqValueCalculator>().As<IValueCalculator>();
var container = builder.Build();
IValueCalculator calc1=container.Resolve<IValueCalculator>();
//IValueCalculator calc = new LinqValueCalculator();
ShoppingCart cart = new ShoppingCart(calc1);
cart.Products = products;
decimal totalValue = cart.CalculateProductTotal();
return View(totalValue);
}
}
}

2.模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace EssentialTools.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }

}
}

3.接口与实现类

//接口

using System.Collections.Generic;

namespace EssentialTools.Models
{
public interface IValueCalculator
{
decimal ValueProducts(IEnumerable<Product> products);
}
}

//实现

using System.Collections.Generic;
using System.Linq;

namespace EssentialTools.Models
{
public class LinqValueCalculator: IValueCalculator
{

public decimal ValueProducts(IEnumerable<Product> products)
{
return products.Sum(m=>m.Price);
}
}
}

4.购物车-业务类

using System.Collections.Generic;

namespace EssentialTools.Models
{
public class ShoppingCart
{
private IValueCalculator calc;
public ShoppingCart(IValueCalculator calcParam)
{
this.calc = calcParam;
}
public IEnumerable<Product> Products { get; set; }
public decimal CalculateProductTotal() {
return calc.ValueProducts(Products);
}

}
}

上一篇:autofac for mvc


下一篇:.net core 3.1 使用autofac注入(一)