6.1.2 Getting Started with Ninject
parent
04a375e7fd
commit
656c976807
|
@ -46,8 +46,10 @@
|
|||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Product.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="ShoppingCart.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
using System.Linq;
|
||||
|
||||
namespace NinjectDemo
|
||||
{
|
||||
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 { set; get; }
|
||||
}
|
||||
|
||||
public interface IValueCalculator
|
||||
{
|
||||
decimal ValueProducts(params Product[] products);
|
||||
}
|
||||
|
||||
public class LinqValueCalculator : IValueCalculator
|
||||
{
|
||||
public decimal ValueProducts(params Product[] products)
|
||||
{
|
||||
return products.Sum(p => p.Price);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,12 +4,23 @@ using System.Linq;
|
|||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Ninject;
|
||||
|
||||
namespace NinjectDemo
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
IKernel ninjectKernel = new StandardKernel();
|
||||
ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
|
||||
|
||||
// get the interface implementation
|
||||
IValueCalculator calcImp1 = ninjectKernel.Get<IValueCalculator>();
|
||||
// create the instance of ShoppingCart and inject the dependency
|
||||
ShoppingCart cart = new ShoppingCart(calcImp1);
|
||||
// perform the calculation and write out the result
|
||||
Console.WriteLine("Total: {0:c}", cart.CalculateStockValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
namespace NinjectDemo
|
||||
{
|
||||
public class ShoppingCart
|
||||
{
|
||||
private IValueCalculator calculator;
|
||||
|
||||
public ShoppingCart(IValueCalculator calcParam)
|
||||
{
|
||||
calculator = calcParam;
|
||||
}
|
||||
|
||||
public decimal CalculateStockValue()
|
||||
{
|
||||
// define the set of products to sum
|
||||
Product[] products =
|
||||
{
|
||||
new Product() { Name = "Kayak", Price = 275M },
|
||||
new Product() { Name = "Lifejacket", Price = 48.95M },
|
||||
new Product() { Name = "Soccer ball", Price = 19.50M },
|
||||
new Product() { Name = "Stadium", Price = 79500M }
|
||||
};
|
||||
|
||||
// calculate the total value of the products
|
||||
decimal totalValue = calculator.ValueProducts(products);
|
||||
|
||||
// return the result
|
||||
return totalValue;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue