我正在尝试使用.NET核心依赖项注入,但是不了解如何为我的方案注入依赖项。我有一个界面
public interface IDataProvider()
{
public int GetData()
}
此接口由两个类实现
public class GoldCustomer:IDataProvider
{
public int GetData()
{
//implementation for gold customer
}
}
另一堂课
public class SilverCustomer:IDataProvider
{
public int GetData()
{
//implementation for silver customer
}
}
现在我正在尝试配置依赖项
public void ConfigureServices(IServiceCollection services)
{
//here i want to inject either gold customer or silver customer based on the scenario
services.AddTransient<IDataProvider, GoldCustomer>();
}
是否可以根据某些条件注入依赖项?
答案 0 :(得分:1)
为GoldCustomer和SilverCustomer创建新的界面。不需要在IGoldCustomer和ISilverCustomer中添加GetData,因为它已经具有IDataProvider的GetData()。
public interface ISilverCustomer : IDataProvider
{
}
public interface IGoldCustomer : IDataProvider
{
}
然后在Startup.cs中注入依赖项
services.AddTransient<IGoldCustomer, GoldCustomer>();
services.AddTransient<ISilverCustomer, SilverCustomer>();
答案 1 :(得分:1)
我希望您应用@Asherguru Answers展示的应用依赖注入后想要实现的目标,或者您可以应用下面说明的Strategy模式示例
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会导致银牌通话,而将钻石级呼叫给其他
答案 2 :(得分:1)
您可以将两个类的依赖项注入到项目中,然后可以将当前项目需要使用的参数GoldCustomer
或SilverCustomer
放入 appsetting.json 文件,然后通过获取appsetting的参数来决定要从哪个类获取返回的数据。
在appsetting.json文件中:
"AppSettings": {
"CurrentCustomer": "SilverCustomer"
}
创建此类以从appsetting.json文件中获取价值:
public class AppSettings
{
public string CurrentCustomer { get; set; }
}
在startup.cs中注入IDataProvider和AppSettings:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddScoped<IDataProvider, GoldCustomer>();
services.AddScoped<IDataProvider, SilverCustomer>();
这是课程:
public interface IDataProvider
{
public int GetData();
}
public class GoldCustomer : IDataProvider
{
public int GetData()
{
return 100;
}
}
public class SilverCustomer : IDataProvider
{
public int GetData()
{
return 200;
}
}
控制器:
public class HomeController : Controller
{
private readonly IEnumerable<IDataProvider> _dataProviders;
private AppSettings AppSettings { get; set; }
public HomeController(MyDbContext context, IEnumerable<IDataProvider> dataProviders, IOptions<AppSettings> settings)
{
_dataProviders = dataProviders;
AppSettings = settings.Value;
}
public IActionResult Index()
{
// this will get the data 200 which returned by SilverCustomer because the AppSettings.CurrentCustomer is SilverCustomer
var message = _dataProviders.FirstOrDefault(h => h.GetType().Name == AppSettings.CurrentCustomer)?.GetData();
}
}
更多详细信息,您也可以参考this。
这是测试结果: