ASP.NET 5 Injection Dependency Injection - Does the [FromServices] attribute only work in the controller?

Using asp.net 5 beta-8, I have something like this registered as a service:

services.AddTransient<IMyClass, MyClass>(); 

When I use this attribute for a property in the controller, myClass set to an IMyClass instance.

 public class HomeController : Controller { [FromServices] public IMyClass myClass { get; set; } public IActionResult Index() { //myClass is good return View(); } } 

However, when I try to use it in a class that does not inherit Controller , it does not seem to set the myClass property to the myClass instance:

 public class MyService { [FromServices] public IMyClass myClass { get; set; } public void DoSomething(){ //myClass is null } } 

Is this the expected behavior? How do I inject my dependencies into a regular class?

+6
source share
2 answers

The problem is that you are calling new MyService() , the ASP.NET 5 injection system is completely ruled out.

To have the dependencies introduced in MyService , we must let ASP.NET create an instance for us.

If you want to use MyService in your controller, you can first register it using a set of services along with IMyClass .

 services.AddTransient<IMyClass, MyClass>(); services.AddTransient<MyService>(); 

In this case, I decided to use constructor injection, so I'm not mistaken in trying to create an instance of MyService myself:

 public class MyService { public IMyClass myClass { get; set; } public MyService(IMyClass myClass) { this.myClass = myClass; } public void DoSomething() { //myClass is null } } 

Now you can enter this service in your controller:

 public class HomeController : Controller { [FromServices] public MyService myService { get; set; } public IActionResult Index() { // myService is not null, and it will have a IMyClass injected properly for you return View(); } } 

If you want to know more about ASP.NET 5 dependency injection system, I made a video and blog here: http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection -in-6-steps /

+6
source

You can use constructor injection for lower level classes ...

 public class MyService { private readonly IMyClass _myClass; public MyService(IMyClass myClass) { if (myClass == null) throw new ArgumentNullException("myClass"); _myClass = myClass; } public void DoSomething() { // Do something } } 
+2
source

All Articles