简体   繁体   中英

Dependency injection (DI) in ASP.Net MVC 6

i was reading a write up on easily dependency 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 inject dependency into project

1st one

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 [Activate] attribute then we do not have to instantiate TimeService by controller constructor injection?

just tell me if we use [Activate] attribute then what will be the advantage ?

if we use [Activate] attribute then what line of code we can eliminate from 1st same code. thanks

The differences between the two code blocks are indeed that the first one leverages Constructor Injection to resolve the dependency on TimeService , while the second example marks a property as one that needs resolving using Property Injection.

What this means is simply that the following constructor becomes redundant:

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

As to why one would opt for Constructor versus Property Injection, I find that trying to have a list of your dependencies clearly listed out in your constructor highlights when a class becomes too dependent, which raises concerns as to what a class is trying to accomplish and, subsequently, makes it a candidate for refactoring.

Property Injection via [Activate] will not be supported from beta5 onwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM