我希望您在应用依赖注入后尝试实现@Asherguru 答案所证明的目标,或者您可以应用下图所示的策略模式示例
namespace DemoInject.Services
{
public interface IStrategy
{
public int GetData();
}
}
namespace DemoInject.Services
{
public interface IDiamondCustomer: IStrategy
{
}
public class DiamondCustomer : IDiamondCustomer
{
public int GetData()
{
return 5000;
}
}
}
namespace DemoInject.Services
{
public interface ISilverCustomer: IStrategy
{
}
public class SilverCustomer : ISilverCustomer
{
public int GetData()
{
return 2000;
}
}
}
开课时
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDiamondCustomer, DiamondCustomer>();
services.AddTransient<ISilverCustomer, SilverCustomer>();
services.AddControllers();
}
在控制器上
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DemoInject.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace DemoInject.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private IStrategy strategy;
private IDiamondCustomer diamondCustomer;
private ISilverCustomer silverCustomer;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IDiamondCustomer diamondCustomer, ISilverCustomer silverCustomer)
{
_logger = logger;
this.diamondCustomer = diamondCustomer;
this.silverCustomer = silverCustomer;
}
[HttpGet("CheckOperation/{Id}")]
public int CheckOperation(int Id)
{
//Basically identify customer if a is even then silver else diamond
if (Id % 2 == 0)
{
this.strategy = this.silverCustomer;
}
else
{
this.strategy = this.diamondCustomer;
}
return this.strategy.GetData();
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
使用偶数调用 CheckOperation 将导致 Silver 调用,而 Diamond 调用 else