Category: .NET Core

DIForFunctions–what it does- part 4

You can find a demo at https://github.com/ignatandrei/FunctionsDI/tree/main/src/FunctionsWithDI  – see TestCOnsoleAPP. But let’s write here also

Generate (constructor) and functions calls similar with ASP.NET Core WebAPI ( [FromServices] will be provided by DI ) Also, verifies for null .

Usage

Reference into the csproj

<ItemGroup>
    <PackageReference Include="RSCG_FunctionsWithDI" Version="2022.6.19.1605" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
    <PackageReference Include="RSCG_FunctionsWithDI_Base" Version="2022.6.19.1605" />
</ItemGroup>	

Then for every class you can write [FromServices]

using RSCG_FunctionsWithDI_Base;
//namespace if necessary
public partial class TestDIFunction
{
    public bool TestMyFunc1([FromServices] TestDI1 t1, [FromServices] TestDI2 t2, int x, int y)
    {
        return true;
    }
    //more functions
}

generates the constructor with needed details

public partial class TestDIFunction
{ 
private TestDI1 _TestDI1;
private TestDI2 _TestDI2;
public TestDIFunction  (TestDI1 _TestDI1,TestDI2 _TestDI2) //constructor generated with needed DI
 { 
this._TestDI1=_TestDI1;
this._TestDI2=_TestDI2;

 } //end constructor 

//making call to TestMyFunc1
public bool TestMyFunc1(int  x,int  y){ 
var t1 = this._TestDI1  ;
if(t1 == null) throw new ArgumentException(" service TestDI1  is null in TestDIFunction ");
var t2 = this._TestDI2  ;
if(t2 == null) throw new ArgumentException(" service TestDI2  is null in TestDIFunction ");
return  TestMyFunc1(t1,t2,x,y);
}

so you can call

var test=serviceProvider.GetService<TestDIFunction>();
Console.WriteLine(test.TestMyFunc1(10,3)); // calling without the [FromServices] arguments

DIForFunctions–NuGet- part3

The important part now is to make public – that means NuGet and documentation, The NuGet is pretty simple – with

dotnet pack

and with GitHub Actions – in order to do automatically every time I modify the main. For now, this is the action

name: .NET

on:

  push:

    branches: [ “main” ]

  pull_request:

    branches: [ “main” ]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

    – uses: actions/checkout@v3

    – name: Setup .NET

      uses: actions/setup-dotnet@v2

      with:

        dotnet-version: 6.0.x

    – name: Restore dependencies

      run: |

        cd src

        cd FunctionsWithDI

        dotnet tool restore

        dotnet pwsh readme.ps1

        dotnet restore

    – name: Build

      run: |

        cd src

        cd FunctionsWithDI

        dotnet build –no-restore

    – name: TestConsoleProject

run:  |

        cd src

        cd FunctionsWithDI

        cd TestConsoleApp

        dotnet run  –no-build

    – name: create package

if: ${{ github.ref == ‘refs/heads/main’ }}

run: |

        cd src

        cd FunctionsWithDI

        echo ‘now aop’

        #dotnet pwsh AOPMethod.ps1

        #dotnet clean 

        #dotnet build

        echo ‘now pack’

        dotnet pack RSCG_FunctionsWithDI/RSCG_FunctionsWithDI.csproj                        -o nugetPackages  –include-symbols –include-source

        dotnet pack RSCG_FunctionsWithDI_Base/RSCG_FunctionsWithDI_Base.csproj              -o nugetPackages  –include-symbols –include-source

    – name: ‘Upload nuget’

      if: ${{ github.ref == ‘refs/heads/main’ }}

      uses: actions/upload-artifact@v2

      with:

        name: RSCG_FunctionsWithDI_${{github.run_number}}

        path: src/FunctionsWithDI/nugetPackages

        retention-days: 1

that generates at every run the packages

You will find the sources at https://github.com/ignatandrei/functionsdi  and the nuget at https://www.nuget.org/packages/RSCG_FunctionsWithDI

DI for Functions- work–part 2

Let’s begin with tests  – we need to have a class with multiple functions that have multiple [FromServices} parameter. Like

public bool TestMyFunc1([FromServices] TestDI1 t1, [FromServices] TestDI2 t2, int x, int y)
         {
             return true;
         }
         public bool TestMyFunc2([FromServices] TestDI1 t12,  int x, int y)
         {
             return true;
         }

// more others

Because there are multiple functions, I need to generate very fast  – so Incremental generators to the rescue . They are documented here : https://github.com/dotnet/roslyn/blob/main/docs/features/incremental-generators.md  . And a good tutorial is to be found at https://andrewlock.net/creating-a-source-generator-part-1-creating-an-incremental-source-generator/ .

Basically, this is the code

IncrementalValuesProvider<MethodDeclarationSyntax> paramDeclarations = context.SyntaxProvider
             .CreateSyntaxProvider(
                 predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
                 transform: static (ctx, _) => GetSemanticTargetForGeneration(ctx))
             .Where(static m => m is not null)!; // filter out attributed enums that we don’t care about

            IncrementalValueProvider<(Compilation, ImmutableArray<MethodDeclarationSyntax>)> compilationAndEnums = context.CompilationProvider.Combine(paramDeclarations.Collect());

            context.RegisterSourceOutput(compilationAndEnums,
             static

and the  idea is to find the parameters of the function that has attributes – and one of those is [FromServices] . After that , find the methods that are the parent – and then the class. After that , is simple to generate a constructor with all (distinct) the [FromServices]parameters and construct the similar method with just the non-DI parameters.

Bonus : We can verify if the parameters are null and throw exception

I could do a template for defining , but – wait to see if gain some traction to modify .

You can find the sources at https://github.com/ignatandrei/functionsdi and the NuGet packages ( one with generator, one with [FromServices] ) at https://www.nuget.org/packages/RSCG_FunctionsWithDI and https://www.nuget.org/packages/RSCG_FunctionsWithDI_Base

Enjoy!

DI for Functions–idea – part 1

Looking at ASP.NET Core , there is a wonderful feature that  gives you thinking :  you can put in any action for a controller FromServices argument and the framework will complete from, well, services: :

public ActionResult Test([FromServices] MyFunction

What if  you can do the same with any function from any class ?

It will be good, but … how  ?  ASP.NET Core instantiate himself the functions, but I cannot do this. 

I can generate with Roslyn a function that takes not DI arguments . For example , from

public bool TestMyFunc1([FromServices] TestDI1 t1, [FromServices] TestDI2 t2, int x, int y)

Roslyn can generate this

public bool TestMyFunc1(int  x,int  y)

And call the previous function – but HOW we can retrieve the arguments ?

As I see , there are 2 options:

1.  Generate a constructor that have as a parameter the ServiceProvider and find the services from ServiceProvider

2. Generate a constructor that have the DI arguments and assign them as fields .

Now go to work!

app.Use vs Middleware–and scoped services

When you want to use a fast middleware , you can use ( pun intended)

app.Use(

However, if you want to use some of scoped services , e.g.

app.Use(async (context, next) =>
{
     var st= app.Services.GetRequiredService<IServerTiming>();

//code

}

then it gives an error

Cannot resolve scoped service  from root provider

For this you should create  a scope:

app.Use(async (context, next) =>
{
     //var st= app.Services.GetRequiredService<IServerTiming>();
     using var sc = app.Services.CreateScope();
     var st = sc.ServiceProvider.GetRequiredService<IServerTiming>();
     st.AddMetric((decimal)0.002, “yrequest”);
     await next(context);
});

However, that means it will NOT be the same scope as the original app . How we can have the same scope ?  By using the middleware

public class ServerTiming : IMiddleware
{
     private readonly IServerTiming serverTiming;

    public ServerTiming(IServerTiming serverTiming)
     {
         this.serverTiming = serverTiming;
     }
     public async Task InvokeAsync(HttpContext context, RequestDelegate next)
     {
         this.serverTiming.AddMetric((decimal)0.001, “startRequest”);
         await next(context);              
     }
}

and registering ( code for .net 6 , you can easy make it for .net <6 )

builder.Services.AddScoped<ServerTiming>();
var app = builder.Build();
app.UseMiddleware<ServerTiming>();

This way we are sure that we have the same scoped data.

Services.Add => 2 NuGet

If you make a NuGet package for ASP.NET Core  and you make an extension method that calls

Services.AddWhatever

in order to add a Sngleton / Scoped / Transient a

IWhatever =>  Whatever

implementation , please add IWhatever in a separate Nuget .

Why ? Because not all ASP>NET Core projects are made of a single project – and , if someone needs constructor injection with IWhatever in his Business Logic , he must not be forced to add the whole asp.net dependencies for just a IWhatever interface

 

Example: The https://www.nuget.org/packages/Lib.AspNetCore.ServerTiming/   –   it depends upon Microsoft.AspNetCore.Http . But I want just  IServerTiming in a business logic. I do not need also the dependency of  IApplicationBuilder .

( and yes, I have started an issue: https://github.com/tpeczek/Lib.AspNetCore.ServerTiming/issues/19 )

Passing from .NET 5 to .NET 6

First, read the document here: Migrate from ASP.NET Core 5.0 to 6.0 | Microsoft Docs .\

So those were my steps ( fully compile after each step ):

1. Replace in csproj net5.0 with net6.0

<TargetFramework>net6.0</TargetFramework>

2.  Update all nugets reference to the latest version

3.  Add globals.cs with various usings

4. Add globals.cs . Mine looks this way ( without the necessary for the project)

global using Microsoft.AspNetCore.Hosting;
global using Microsoft.AspNetCore.Http;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using System;
global using System.Collections.Generic;
global using System.Linq;
global using System.Threading.Tasks;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.AspNetCore.Mvc.ApiExplorer;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Options;
global using Microsoft.OpenApi.Models;
global using Swashbuckle.AspNetCore.SwaggerGen;
global using Microsoft.AspNetCore.Builder;
global using AMSWebAPI;
global using appSettingsEditor;
global using HealthChecks.UI.Client;
global using Hellang.Middleware.ProblemDetails;
global using Microsoft.AspNetCore.Diagnostics.HealthChecks;
global using Microsoft.AspNetCore.HttpOverrides;
global using NetCore2BlocklyNew;

5.  Move away from Startup – put all in program .cs  – easy : services moved to app.Services , and instead of parameters in configure, use the app.Services – example

var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

6.  Tests

I have a problem with  “ The server has not been started or no web application was configured. “  -when I configure WebApplicationFactory<Program> 

Reading Minimal APIs in .NET 6 but where are the Unit Tests? – Scott Hanselman’s Blog 

Testing in .NET 6 with WebApplicationFactory (including Minimal APIs) | by Lee Dale | Medium

Supporting integration tests with WebApplicationFactory in .NET 6: Exploring .NET 6 – Part 6 (andrewlock.net)

Integration tests in ASP.NET Core | Microsoft Docs

No avail yet.  Should study ore.

Templating Roslyn Source Code Generators

I want that , when I generate code with Roslyn, to have a template that I can easy modify to generate code . Also, I want to let the user ( the programmer , in this case) modify this template  – maybe he has better ideas than me.

For reading from the RSCG, is pretty simple: Make as an embedded resource and read with

internal class EmbedReader
{
     static Assembly assembly;
     static EmbedReader()
     {
         assembly = Assembly.GetExecutingAssembly();

    }
     public static string ContentFile(string name)
     {
         var resourceName = name;

        using (Stream stream = assembly.GetManifestResourceStream(resourceName))
         using (StreamReader reader = new StreamReader(stream))
         {
             string result = reader.ReadToEnd();
             //this is the content
         }
     }
}

For let the programmer user put his template, put as as additional file in the csproj

<ItemGroup>
         <AdditionalFiles Include=”context.txt”  />

</ItemGroup>

and read with

var file = context.AdditionalFiles.Where(it => it.Path.EndsWith($”{val}.txt”))
                     .Select(it => it.GetText())
                     .FirstOrDefault();

            if (file != null)
             {
                 content = string.Join(Environment.NewLine, file.Lines.Select(it => it.ToString()));
             }

To do both,if the result of the first is empty, read the second (or opposite ? )

[NuGet]: Transplator

This is a Nuget that it is what Razor should have been. It is a Roslyn Source Code Generator that transforms template into code.

Link: https://www.nuget.org/packages/Transplator 

Site: https://github.com/atifaziz/Transplator

What it does:  Takes a template and generates source code for outputting anything inside.

Usage:

Somewhere in the csproj:

<ItemGroup>
   <CompilerVisibleProperty Include=”DebugTransplator” />
   <CompilerVisibleItemMetadata Include=”AdditionalFiles” MetadataName=”SourceItemType” />
   <CompilerVisibleItemMetadata Include=”AdditionalFiles” MetadataName=”Name” />
   <AdditionalFiles Include=”ASM.txt” SourceItemType=”Transplate” KeepMetadata=”Name” />

</ItemGroup>

Somewhere in a .cs file

var response = new ASMTemplate().Render();

And the template

partial class ASMTemplate
{
     StringBuilder sb = new StringBuilder();
     public void WriteText(string text)
     {
         sb.AppendLine(text);
     }
     public void WriteValue(int text)
     {
         sb.AppendLine(“”+text);
     }  
     public void WriteValue(int? text)
     {
         if(text != null)
             sb.AppendLine(“” + text);
     }
     public void WriteValue(DateTime text)
     {
         sb.AppendLine(text.ToString(“yyyy MMMM dd HH:mm:ss”));
     }
     public void WriteValue(string text)
     {
         sb.AppendLine(text);
     }
     public string Render()
     {        
         this.RenderCore();
         return sb.ToString();
     }
}

[RSCG]–About My Software

I have made a new improvement to my Roslyn Source Code Generator, AMS . Until now it just said the time and the commit date in a CI scenario  ( Git ( GitLab, GitHub), Azure …)

Now –  what if it can list all the merge requests between 2 dates  , so you can see what is new ? 

Now you can have – see this:

What you need to do  ?

Just add the following codes

using AMS_Base;
[assembly:VersionReleased(Name=”PreviousReleases”,ISODateTime =”2022-03-31″,recordData = RecordData.Merges)]
[assembly: VersionReleased(Name = “WithVersioning”, ISODateTime = “2022-04-02”, recordData = RecordData.Merges)]
[assembly: AMS_Base.VersionReleased(Name = “FutureRelease”, ISODateTime = “9999-04-16”, recordData = AMS_Base.RecordData.Merges)]

( Of course , you should read first how to add the NuGet package – see https://github.com/ignatandrei/RSCG_AMS/blob/main/README.md )

How it is made  ?

First, we should find Git –  start a process with

Where git.exe

or

which git

to find the location.

Second, start a process with the location of the git find below

log –merges –pretty=””%an|%cs|%H|%s

to see the merges . Then merge with the dates

assembly:VersionReleased 

that are registered before – and this is all !

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.