Dependency injection is very flexible in MVC6 architecture.
Now, it’s possible to inject dependency only in action level.
Earlier, if there was need to inject dependency then there
were three possible ways
1) Constructor injection
2) Function injection
3) Property injection
Now, the common part of these technique is, it will resolve
dependency in class level. So, if there is need to resolve dependency only in
one function those techniques are not best fit.
In MVC6 Microsoft has introduce injection in function level.
Just we need to use [FromService]
attribute in parameter and it will resolve
dependency from IoC container.
Let’s implement small example to understand the same. Here
is implementation of Message service.
public interface IMessage
{
string Message { get; set; }
}
public class Message : IMessage
{
string _message;
string IMessage.Message
{
get
{
_message = "System message";
return _message;
}
set
{
_message = value;
}
}
}
Message class has implemented IMessage interface. Now, we
have to register those in IoC container of MVC6. I am using default IoC
container in this example.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMessage, Message>();
}
All done, now we are allowed to resolve dependency from action
using “FromService” attribute.
public IActionResult Index([FromServices] IMessage Today)
{
string message = Today.Message;
return View();
}