[. NET Core] simple use of built-in Mvc IOC and mvcioc
This article is based on. NET Core 2.0.
In view of the many theories of online articles, I want to organize a Hello World (Demo) article.
Because the built-in Ioc of Mvc is used, you do not need to use Nuget to install other class libraries for reference.
Scenario 1: use of simple classes
Class DemoService. cs:
public class DemoService { public string Test() { return Guid.NewGuid().ToString(); } }
Controller DemoController. cs:
public class DemoController : Controller { private readonly DemoService _demoService; public DemoController(DemoService demoService) { _demoService = demoService; } public IActionResult Index() { return Json(_demoService.Test()); } }
You must register the ConfigureServices () method in Startup. cs before using it. Three methods are provided here. You can register the ConfigureServices () method as you like.
// Method 1 services. addSingleton (typeof (DemoService), new DemoService (); // method 2 services. addSingleton (typeof (DemoService); // method 3 services. addSingleton <DemoService> ();
The output result is normal:
// Example services. AddTransient (typeof (DemoService ));
Services. AddScoped <DemoService> ();
Scenario 2: Use of interface classes
Interface IDemo2Service. cs:
public interface IDemo2Service { string Test(); }
Demo2Service. cs:
public class Demo2Service : IDemo2Service { public string Test() { return Guid.NewGuid().ToString(); } }
Controller Demo2Controller. cs:
public class Demo2Controller : Controller { private readonly IDemo2Service _demoService; public Demo2Controller(IDemo2Service demoService) { _demoService = demoService; } public IActionResult Index() { return Json(_demoService.Test()); } }
The registration method added to the ConfigureServices () method in Startup. cs is as follows:
// Method 1 services. addSingleton (typeof (IDemo2Service), new Demo2Service (); // method 2 services. addSingleton (typeof (IDemo2Service), typeof (Demo2Service); // method 3 services. addSingleton <IDemo2Service, Demo2Service> ();
The output result is normal:
Scenario 3: Use of referenced Class Libraries