`
wsql
  • 浏览: 11785831 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Ninject--ASP.NET MVC 3中的依赖注入容器

 
阅读更多

可以采用Ninject作为ASP.NET MVC 3依赖注入容器,下面演示其具体用法:

1、编写如下代码:

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; }
}

public interface IValueCalc
{
decimal ValueProducts(params Product[] prods);
}

public class LinqValueCalc : IValueCalc
{
public System.Decimal ValueProducts(params Product[] prods)
{
return prods.Sum(p => p.Price);
}
}

public class ShoppingCart
{
private IValueCalc calc;
public ShoppingCart(IValueCalc ivc)
{
calc = ivc;
}
public decimal Total()
{
var prods = new[]
{
new Product{Name ="a",Price =15},
new Product{Name="b",Price =25},
new Product{Name ="c",Price =35}
};
return calc.ValueProducts(prods);
}
}

2、在安装插件使得vs2010能开发ASP.NET MVC3项目时,vs2010同时也会安装NuGet(一个插件:可以让你在开发项目时,通过NuGet在线查找一些插件,并安装到自己的项目中。具体大家可以百度NuGet是什么,干什么用的),通过Add Library Package Reference(右击解决方案中的项目,在快捷菜单中)找到ninject,单击“Install”就完成了ninject插件的引用。

3、然后再添加:using Ninject;

4、在主入口书写如下代码:

static void Main(string[] args)
{
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<IValueCalc>().To<LinqValueCalc>();//将接口绑定到实现
IValueCalc cal = ninjectKernel.Get<IValueCalc>();
Console.WriteLine("Total:{0:C}", new ShoppingCart(cal).Total());
Console.ReadKey();
}

5、运行即可

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics