Dependency Injection (DI) in ASP.Net MVC 6

I read the entry for easy dependent injection in ASP.Net MVC 6 from this URL http://weblogs.asp.net/scottgu/introducing-asp-net-5

they show how very easily we can add dependency to a project

1st number

namespace WebApplication1 { public class TimeService { public TimeService() { Ticks = DateTime.Now.Ticks.ToString(); } public String Ticks { get; set; } } } register the time service as a transient service in the ConfigureServices method of the Startup class: public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddTransient<TimeService>(); } public class HomeController : Controller { public TimeService TimeService { get; set; } public HomeController(TimeService timeService) { TimeService = timeService; } public IActionResult About() { ViewBag.Message = TimeService.Ticks + " From Controller"; System.Threading.Thread.Sleep(1); return View(); } } 

2nd one

 public class HomeController : Controller { [Activate] public TimeService TimeService { get; set; } } 

now see the second code. are they trying to say that if we use the [Activate] attribute, we don’t need to instantiate the TimeService using the controller constructor inline?

just tell me if we use the [Activate] attribute that will be an advantage?

if we use the [Activate] attribute, then which line of code can we exclude from the first code. thanks

+6
source share
1 answer

The differences between the two code blocks are that the first one uses the Constructor Injection to resolve the dependency on the TimeService , and the second example is a property that needs to be resolved using Injection.

This means that the following constructor becomes redundant:

 public HomeController(TimeService timeService) { TimeService = timeService; } 

Regarding why Constructor versus Injection could be chosen, I found that trying to see a list of your dependencies explicitly listed in your constructor is highlighted when the class becomes too dependent, which raises concerns that the class is trying to execute and, subsequently, make him a refactoring candidate.

Inserting properties through [Activate] not supported since beta5.

+12
source

Source: https://habr.com/ru/post/982945/


All Articles