Friday, December 18, 2015

Inject service to View in MVC6


This is new feature of MVC6, you can inject service to view directly. It will help to push/pull data from UI to business logic directly by skipping controller layer.

Here, we will implement small example to demonstrate the concept.
      
     1)      At first we will create one simple service like this.

namespace MVC6Web.Services
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class DataService
    {
        Person _person;
        public DataService()
        {
            _person = new Person
            Id = 1, Name = "Sourav Kayal" };
        }

        public Person GetPerson()
        {
            return _person;
        }
    }
}

DataService is simple C# class containing GetPerson() function which will return an object of Person class.
      
      2)      Make the service visible to MVC environment.
 In this point we will attach DataService to environment of current project. So, modify the ConfigureService function like below.

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MVC6Web.Services.DataService>();
}
      
      3)      Inject DataService to view.
This is the final step, here we will inject the service to view. Here is the procedure to get it done.

@inject MVC6Web.Services.DataService DataService   

<ul>
    <li>Item : @DataService.GetPerson().Name</li>
</ul>

The format to inject to Service is like this.

@inject <ServicePath> <Identifier>

Once we inject service, we are allowed to call GetPerson() function from view itself, though the function is not part of controller.


 




No comments:

Post a Comment