1.创建一个web api项目
2.在项目中创建一个接口类
namespace LearnCore.CoreDI { public interface ILearnDI { string GetName(string argName); } }
3.为接口类创建一个实现类
public class LearnDI : ILearnDI { public string GetName(string argName) { return $"我的名字是:{argName}"; } }
4.在startup文件中创建 映射关系
public void ConfigureServices(IServiceCollection services) { services.AddScoped<ILearnDI, LearnDI>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
5.在控制器中注入,并使用
namespace LearnCore.CoreDI.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly ILearnDI learnDI; public ValuesController(ILearnDI arglearnDI) { this.learnDI = arglearnDI; } [HttpGet(nameof(GetName))] public string GetName() { return learnDI.GetName("希望"); } } }