Search This Blog

2020/12/10

FromServices Attribute in ASP.NET Core

 We are do Dependency injection directly into controller action using FromServices attribute.

Lets see how we can accomplish this.I have a ASP.NET Core WebAPI Project which i will use for demonstration purpose.

First we create a service & its interface as follows

IRainService.cs

public interface IRainService

{

int GetRainEstimate(string location);

}

RainService.cs

public class RainService : IRainService

{

public int GetRainEstimate(string location)

{

     //logic to dynamically get Rain Forecast

      return 10;

}

}


Now we can these to classes straightly head to ConfigureServices in startup.cs

StartUp.cs


public void ConfigureServices(IServiceCollection services)

{


services.AddControllers();

services.AddTransient<IRainService, RainService>();

}


Now in Our Controller Action we add IRainService as method parameter with FromService attribute as follows.


WeatherForecastController.cs


public IEnumerable<WeatherForecast> Get([FromServices] IRainService RainService)

{

var rainInMlmtr = RainService.GetRainEstimate("mumbai");

//other code of controller

}


Inside this action method we can now access RainService class and call its method & property due to Dependency Injection in Controller Action.





POSTGRESQL - LINQ -ASP.NET CORE CONSOLE APPLICATION

create a console application using dotnet cli.

    dotnet new console --name DiConsoleAp

 

Now create a folder models and add Product.cs

Product.cs

namespace DiConsoleApp.Models

{

public class Product

{

public int id { get; set; }

public string name { get; set; }

}

}


Now in database create a table

CREATE TABLE public."Products"

(

id integer NOT NULL DEFAULT nextval('"Products_id_seq"'::regclass),

name character varying(50) COLLATE pg_catalog."default" NOT NULL,

CONSTRAINT "Products_pkey" PRIMARY KEY (id)

)


I am using postgresql as my database.


create DBContext class EfContext.cs in models folder as


EfContext.cs


using Microsoft.EntityFrameworkCore;

using DiConsoleApp.Models;

using Microsoft.Extensions.Configuration;

using System;

using System.IO;


namespace DiConsoleApp.Models

{

public class EFContext : DbContext

{

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

IConfigurationRoot configuration = new ConfigurationBuilder()

.SetBasePath(Directory.GetCurrentDirectory())

.AddJsonFile("appsettings.json")

.Build();


optionsBuilder.UseNpgsql(configuration.GetConnectionString("Connectionstring"));

}

public DbSet<DiConsoleApp.Models.Product> Products { get; set; }


protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Product>(entity =>

{

entity.HasKey(e => e.id);

});

}

}

}




create a new folder services in in add productService.cs


productService.cs


using System;

using Microsoft.Extensions.Configuration;

using System.Collections.Generic;

using System.Linq;

using DiConsoleApp.Models;


namespace DiConsoleApp.Services

{

public class ProductService

{

public static bool InsertProduct(string productName)

{

using (var db = new EFContext())

{

if(productName.Length > 0)

{

Product product = new Product();

product.name = productName;

db.Add(product);

db.SaveChanges();

return true;

}

else

{

return false;

}

}

}

public static bool updateProduct(int productId,string productName)

{

using (var db = new EFContext())

{

Product product = db.Products.Find(productId);


if(product != null)

{

product.name = productName;

db.SaveChanges();

return true;

}else{

return false;

}

}

}


public static bool deleteProduct(int productId)

{

using (var db = new EFContext())

{

Product product = db.Products.Find(productId);


if(product != null)

{

db.Products.Remove(product);

db.SaveChanges();

return true;

}

else

{

return false;

}

}

}


public static void readProduct()

{

using (var db = new EFContext())

{

List<Product> products = db.Products.ToList();

foreach (Product p in products)

{

Console.WriteLine("{0} {1}", p.id, p.name);

}

}

return;

}

}

}


In Program.cs we will do CRUD operations as follows.


Program.cs


using System;

using Microsoft.Extensions.DependencyInjection;

using System.Linq;

using DiConsoleApp.Models;

using System.Collections.Generic;

using DiConsoleApp.Services;


namespace DiConsoleApp

{

class Program

{

static void Main(string[] args)

{

/*linq*/

ProductService.readProduct();

//INSERT

if (ProductService.InsertProduct("INK Pen")==true)

{

Console.WriteLine("INK PEN INSERTED");

}


//UPDATE

if (ProductService.updateProduct(3,"THE INK Pen")==true)

{

Console.WriteLine("INK PEN Updated");

}


//DELETE

if(ProductService.deleteProduct(3)==true)

{

Console.WriteLine("INK Pen Deleted");

}

}

}


}


Code for this can be found out at https://github.com/gitsangramdesai/aspnetcore-console-DI-LINQ