Few days ago there was a long discussion going on in .Net MVC team between [Activate] and @inject.
But recently they have announced that they are getting loud and clear positive feedback for @inject
Ok, so first of all what is inject for?
You might have seen this before whether in Java or in spring. Now this is going to be used as a directive in MVC.
As the name suggests it is used for dependency injection. @inject supports injecting anything the container can resolve.
Wait, is it for Razor View?
Oh , Yes it is!
It is nothing but a new page directive which allows you to inject some method calls from a class or service directly into your view.
Confused?
Let us understand this by a simple example!
Suppose i have a ProductRepositry class in which i am having different methods as below:
using System.Threading.Tasks; namespace InjectDemo.Models { private ProductManager _manager = new ProductManager(); public async Task<int> GetProducts() { return await Task.FromResult(_manager.GetAll.Count()); } public async Task<int> GetProductById(int id) { return await Task.FromResult(_manager.GetProductById(id)); } public async Task<int> GetProductByName(string id) { return await Task.FromResult(_manager.GetProductByName(id)); } }
and in view:
@model System.Collections.IEnumerable
@inject InjectDemo.Models.ProductRepository Stats
<h3>My Products</h3>
<ul>
@foreach (var p in Model)
{
<li>@string.Format("{0} {1}", p.Name, p.Type)</li>
}
</ul>
<div>
<span>Product Number 1 : @await Stats.GetProductById(1)</span>
<br/>
<span>Product X: @await Stats.GetHeroCountByType("X")</span>
<br/>
<span>Ttal Count: @await Stats.GetProducts()</span>
</div>
Awesome, so now should it work?
Wait we need to add something more.
we need to configure the AddTransient() method by adding the ProductRepository model into it. So the Configure method would now look like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient < InjectDemo.Models.ProductRepository > ();
}
Voila!
By the way if @inject is for razor then what is for MVC ?
It WAS [Activate].
the reason for using “WAS” is it is recently removed by .Net team due to the feedback.
So as stated by .Net team:
[Activate]
is gone – we’d rather plug in a 3rd party DI for users who want property injection. There’s a consistency issue with MVC providing this and other parts of Asp.Net which don’t.
.Net team is working so hard to make it easy for all .Net developers and still asking for feedback.
I will update once updated by .Net team about @inject and related things.
Till then stay tuned for more updates.
One thought on “@inject : New directive of MVC”