6.1.2 Getting Started with Ninject

chap6
Jason Zhu 2021-08-10 22:22:37 +10:00
parent 04a375e7fd
commit 656c976807
4 changed files with 69 additions and 0 deletions

View File

@ -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" />

View File

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

View File

@ -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());
}
}
}

View File

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