Get the App
SLTechnology News&Howtos  ›  Network Security  › 

The use of IOC in Mvc

Shulou Source: shulou.com Published: 2022-06-01 06:01:40 10月04日 Update

IOC is the abbreviation of control inversion (Inversion of Control), which is generally divided into two types: dependency injection (Dependency Injection) and dependency search (Dependency Lookup). Dependency injection is widely used. This article will briefly talk about the use of IOC dependency injection in MVC.

I created a new mvc project and wrote this in HomeController:

1 public DataService dataService {get; set;} 2 3 public HomeController (DataService dataService) 4 {5 this.dataService = dataService;6}

Where the DataService class is a class that I wrote to provide data:

1 public class DataService 2 {3 private IRepository repos {get; set;} 4 5 public DataService (IRepository repo) 6 {7 repos = repo; 8} 9 10 public IEnumerable GetData () 11 {12 return repos.GetData (); 13} 14 15}

1 public interface IRepository2 {3 IEnumerable GetData (); 4}

1 public class DataRepository: IRepository 2 {3 4 public DataRepository () 5 {6 7} 8 9 public IEnumerable GetData () 10 {11 List list = new List (); 12 list.Add ("test1"); 13 list.Add ("test2"); 14 list.Add ("test3"); 15 list.Add ("test4") 16 list.Add ("test5"); 17 list.Add ("test6"); 18 return list;19} 20}

Then run the project, and the page will show a result like this:

The error reported is that the interface is not registered, resulting in an error in construction. How to solve it? IOC can be solved perfectly.

First add related class libraries, right-click manager Nuget packages to search for unity

Add the following two, and you will find that something new has been added to the project:

Then we can do IOC dependency injection.

Add a sentence to the RegisterTypes method in UnityConfig.cs

1 Container.RegisterType ()

Where IRepository is the interface of the parameters in the constructor we want to inject, and DataRepository is the concrete implementation of this interface.

Or I write something like this:

1 container.RegisterType (2 new InjectionConstructor (3 new ResolvedParameter () 4))

It's all okay.

So that we can run the project correctly.

The code in Action:

1 public ActionResult Index () 2 {3 IEnumerable list = dataService.GetData (); 4 return View (list); 5}

In View:

1 @ model IEnumerable 2 @ {3 ViewBag.Title = "Home Page"; 4} 5 6 7 8 9 @ foreach (var item in Model) 10 {11 @ item12} 13 14

The effect displayed is:

Tags: Project interface method control run thing two code usage function parameter effect data time shorthand type result page English application Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Tech Info macOS Apple Redmi