1.新建两个文件
public interface ICounter { int Get(); } public class Counter : ICounter { int i; public int Get() { return i++; } }
2.启动时注册
//单例模式 services.AddSingleton<ICounter, Counter>();
3.构造函数注入
public class HomeController : Controller { private ICounter _counter; public HomeController(ICounter counter) { _counter = counter; } public IActionResult Index() { int count = _counter.Get(); return Content(count.ToString()); } }