Ninject基础(转载)

转载自http://www.cnblogs.com/tylerdonet/p/3297915.html

Don't call me,I will call you.

Ninject是一个IOC容器用于解决组件中的耦合问题,他的目的在于做到最少的配置。其他的IOC工具过于依赖配置文件,需要使用assembly-qualified名称来进行定义,容易出错。但是Ninject不能进行热插拔。(汗,这不是IOC的主要优点吗?)

具体实现:

    public interface IValueCalculater
    {
        decimal ValueProducts(params Product[] products);
    }
    public class LinqValueCalculator : IValueCalculater
    {
        public decimal ValueProducts(params Product[] products)
        {
            return products.Sum(p => p.Price);
        }
    }
    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 class ShoppingCat
    {
        protected IValueCalculater calculater;
        protected Product[] products;

        public ShoppingCat(IValueCalculater calculater)
        {
            this.calculater = calculater;
            products = new Product[]{ 
                                        new Product(){Name="Kayak" , Price=275M},
                                        new Product(){Name="Lifejacket" , Price=48.95M},
                                        new Product(){Name="Scooceer ball" , Price=19.5M},
                                        new Product(){Name="Stadium" , Price=79550M}
                                    };

        }

        public virtual decimal CalculatStockValue()
        {
            decimal totalPrice = calculater.ValueProducts(products);
            return totalPrice;
        }
    }

===》

    class Program
    {
        static void Main(string[] args)
        {
            IKernel ninjectKernel = new StandardKernel();
            ninjectKernel.Bind<IValueCalculater>().To<LinqValueCalculator>();

            IValueCalculater calcImpl = ninjectKernel.Get<IValueCalculater>();
            ShoppingCat cart = new ShoppingCat(calcImpl);
            Console.WriteLine(cart.CalculatStockValue());
            Console.Read();
        }
    }

 

posted @ 2015-06-23 14:49  江境纣州  阅读(110)  评论(0编辑  收藏  举报