Using NInject Do DI(3) In Asp.net MVC4
1.Install NInject , open Nuget
2.Add CheckoutInterface & Implementation:
ICheckout.cs
CustomerCheckout.cs
EmployeeCheckout.cs
Codes :
public interface ICheckout
{
dynamic GetTotal(dynamic prices);
string DiscountName { get; }
}
public classCustomerCheckout:ICheckout
{
private IDiscount _discount;
public CustomerCheckout(IDiscountdiscount)
{
_discount = discount;
}
public dynamic GetTotal(dynamic prices)
{
dynamic total=0;
for (int i = 0; i <prices.Length; i++)
{
total += prices[i];
}
return_discount.WithDiscount(total);
}
public string DiscountName
{
get { return_discount.GetType().FullName; }
}
}
public class EmployeeCheckout : ICheckout
{
private IDiscount _discount;
public EmployeeCheckout(IDiscountdiscount)
{
_discount = discount;
}
/// <summary>
/// Employee enjoy half Price
/// </summary>
/// <paramname="prices"></param>
/// <returns></returns>
public dynamic GetTotal(dynamic prices)
{
dynamic total = 0;
for (int i = 0; i <prices.Length; i++)
{
total += prices[i];
}
return _discount.WithDiscount(total* 0.5);
}
public string DiscountName { get {return _discount.GetType().FullName; } }
}
3.Add Discount Interface & Implementations :
IDiscount.cs
DiscountNormalPrice.cs
DiscountHalf.cs
Codes :
public interface IDiscount
{
dynamic WithDiscount(dynamic price);
}
public classDiscountNormalPrice:IDiscount
{
public dynamic WithDiscount(dynamicprice)
{
return price;
}
}
public classDiscountHalf : IDiscount
{
public dynamic WithDiscount(dynamicprice)
{
return price * 0.5;
}
}
4.Add DI Resolver
Implementation :
public class DIResolver :IDependencyResolver
{
private IKernel kernel;
public DIResolver()
{
kernel = new StandardKernel();
ServeCustomerDiscountSeason();
//ServeCustomerNoDiscount();
//ServeEmployeeDiscountSeason();
// ServeEmployeeNoDiscount();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void ServeCustomerDiscountSeason()
{
kernel.Bind<ICheckout>().To<CustomerCheckout>();
kernel.Bind<IDiscount>().To<DiscountHalf>();
}
private void ServeCustomerNoDiscount()
{
kernel.Bind<ICheckout>().To<CustomerCheckout>();
kernel.Bind<IDiscount>().To<DiscountNormalPrice>();
}
private void ServeEmployeeDiscountSeason()
{
kernel.Bind<ICheckout>().To<EmployeeCheckout>();
kernel.Bind<IDiscount>().To<DiscountHalf>();
}
private void ServeEmployeeNoDiscount()
{
kernel.Bind<ICheckout>().To<EmployeeCheckout>();
kernel.Bind<IDiscount>().To<DiscountNormalPrice>();
}
}
For Demonstration , will apply these bindings one by one later .
5.In HomeController.cs :
public string Index()
{
var oriPrice = new []{15,16,14,20};
var total =_checkout.GetTotal(oriPrice);
return string.Format(
"Checkout Strategy : {0} , DiscountStrategy : {1} , Total : {2}",
_checkout.GetType().FullName,_checkout.DiscountName,total);
}
6.Open Global.asax
In Application_Start , Apply Dependency Resolver :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
DependencyResolver.SetResolver(new DIResolver());
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
7.Apply bindings in DIResolver.cs one by one willget the follow results :
Summary :
1. The MVC Framework received the request and figured out that the request is
intended for the Home controller .
2. The MVC Framework asked our custom dependency resolver class to create a
new instance of the Home Controller class, specifying the class using the Type
parameter of the GetService method.
3. Our dependency resolver asked Ninject to create a new Home Controller class by
passing on the Type object to the TryGet method.
4. Ninject inspected the Home Controller constructor and found that it requires an
IValueCalculator implementation, which it knows that it has a binding for.
5. Ninject creates an instance of the LinqValueCalculatorclass and uses it to
create a new instance of the HomeController class.
6. Ninject passes the newly-created HomeController instance to the custom
dependency resolver, which returns it to the MVC Framework.The MVC
Framework uses the controller instance to service the request.
相關文章
- HMI 10.1 DO DI 的測試。
- 《Asp.Net Core3 + Vue3入坑教程》 - 3.AutoMapper & Restful API & DIASP.NETVueAPPRESTAPI
- ASP.NET Core依賴注入(DI)ASP.NET依賴注入
- ASP.NET Core 依賴注入(DI)ASP.NET依賴注入
- 淺談ASP.NET Core中IOC與DI的理解和使用ASP.NET
- Core官方DI解析(3)-ServiceCallSite.md
- ASP.NET MVC不可或缺的部分——DI及其本質工作分析ASP.NETMVC
- .net 溫故知新【13】:Asp.Net Core WebAPI 使用依賴注入DIASP.NETWebAPI依賴注入
- 今天的工作do了嗎 微do吧 也沒有全do
- Using Geometry to Detect Grasp Poses in 3D Point Clouds3DCloud
- Net6 DI原始碼分析Part3 CallSiteRuntimeResolver,CallSiteVisitor原始碼
- MySQL 索引優化 Using where, Using filesortMySql索引優化
- Spring-DISpring
- MySQL explain結果Extra中"Using Index"與"Using where; Using index"區別MySqlAIIndex
- IIS7 中部署MVC4應用程式需要怎麼做?MVC
- 手把手教你寫DI_3_小白徒手支援 `Singleton` 和 `Sc
- DIP、IoC、DI、JSJS
- Spring(IOC&DI)Spring
- 六-Docker DI、CDDocker
- 【Spring】IOC&DISpring
- 深圳scala-meetup-20180902(3)- Using heterogeneous Monads in for-comprehension with Monad TransformerORM
- 6月書訊:Di li li li di li li li...
- Using hints for PostgresqlSQL
- String interpolation using $
- using的用法
- Using mysqldump for backupsMySql
- MySQL 之 USINGMySql
- What does -> do in clojure?
- Do Evil Things with gopher://Go
- 善用 do-whileWhile
- DI 原理解析 並實現一個簡易版 DI 容器
- Docker & ASP.NET Core (3):釋出映象DockerASP.NET
- CRS-2101:The OLR was formatted using version 3 ORACLE單機ASM報錯ORMOracleASM
- spring IOC/DI筆記Spring筆記
- Spring 依賴注入 DISpring依賴注入
- 了不起的 IoC 與 DI
- 基於XML的DIXML
- 深入理解 IoC、DI
- IOC與DI總結