Reputation: 179
Using asp.net 5 beta-8, I have something like this registered as a service:
services.AddTransient<IMyClass, MyClass>();
When I use this attribute on a property in a controller, myClass
gets set to the instance of the IMyClass
.
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 which doesn't inherit Controller
, it doesn't seem to set the myClass
property to an instance of IMyClass
:
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 in a regular class?
Upvotes: 9
Views: 9069
Reputation: 6401
The problem is when you call new MyService()
, the ASP.NET 5 dependency injection system is totally bypassed.
In order to have dependencies injected into MyService
, we need to let ASP.NET create the instance for us.
If you want to use MyService
in your controller, you can have to first register it with the services collection along with IMyClass
.
services.AddTransient<IMyClass, MyClass>();
services.AddTransient<MyService>();
In this case, I chose to use constructor injection so I don't make the mistake of trying to instantiate 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 are free to inject this service into 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 learn more about the ASP.NET 5 dependency injection system, I made a video and blog post here: http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/
Upvotes: 4
Reputation: 5578
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
}
}
Upvotes: 2