描述依赖关系的首选方法是使用构造函数注入,它遵循显式依赖性原则:
ITestService.cs
public interface ITestService { int GenerateRandom(); }
TestService.cs
public class TestService : ITestService { public int GenerateRandom() { return 4; } }
Startup.cs(ConfigureServices)
public void ConfigureServices(IServiceCollection services) { // ... services.AddTransient<ITestService, TestService>(); }
HomeController.cs
using Microsoft.Extensions.DependencyInjection; namespace Core.Controllers { public class HomeController : Controller { public HomeController(ITestService service) { int rnd = service.GenerateRandom(); } } }