【发布时间】:2015-02-24 13:08:30
【问题描述】:
我正在从这个 url http://weblogs.asp.net/scottgu/introducing-asp-net-5
阅读一篇关于在 ASP.Net MVC 6 中轻松进行依赖注入的文章他们展示了我们可以多么容易地将依赖项注入项目
第一个
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();
}
}
第二个
public class HomeController : Controller
{
[Activate]
public TimeService TimeService { get; set; }
}
现在看第二个代码。他们是否想说如果我们使用[Activate] 属性,那么我们不必通过控制器构造函数注入来实例化TimeService?
告诉我如果我们使用[Activate] 属性那么会有什么优势?
如果我们使用[Activate] 属性,那么我们可以从第一个相同的代码中删除哪一行代码。谢谢
【问题讨论】:
标签: c# asp.net-mvc dependency-injection asp.net-core-mvc