RSCG – RSCG_FunctionsWithDI
| name | RSCG_FunctionsWithDI |
| nuget | https://www.nuget.org/packages/RSCG_FunctionsWithDI/ |
| link | https://github.com/ignatandrei/functionsdi |
| author | Andrei Ignat |
Generating functions that have parameters from services
This is how you can use RSCG_FunctionsWithDI .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RSCG_FunctionsWithDI" Version="2022.7.7.636" ReferenceOutputAssembly="false" OutputItemType="Analyzer" />
<PackageReference Include="RSCG_FunctionsWithDI_Base" Version="2022.7.7.636" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
</ItemGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
</Project>
The code that you will use is
// See https://aka.ms/new-console-template for more information using Microsoft.Extensions.DependencyInjection; using RSCG_FunctionsWithDIDemo; var services = new ServiceCollection(); services.AddSingleton<TestDIMyClass>(); services.AddSingleton<TestDI1>(); services.AddSingleton<TestDI2>(); var serviceProvider = services.BuildServiceProvider(); var test = serviceProvider.GetRequiredService<TestDIMyClass>(); Console.WriteLine("the TestMyFunc1 is not called with [FromServices] parameters " +test.TestMyFunc1(10,3));
namespace RSCG_FunctionsWithDIDemo;
public class TestDI1
{
public int x;
}
namespace RSCG_FunctionsWithDIDemo;
public class TestDI2
{
public int x;
}
using RSCG_FunctionsWithDI_Base;
namespace RSCG_FunctionsWithDIDemo;
public partial class TestDIMyClass
{
public bool TestMyFunc1([FromServices] TestDI1 t1,[FromServices] TestDI2 t2,int x,int y)
{
return true;
}
}
The code that is generated is
namespace RSCG_FunctionsWithDIDemo
{
public partial class TestDIMyClass
{
private TestDI1 _TestDI1;
private TestDI2 _TestDI2;
public TestDIMyClass
(TestDI1 _TestDI1,TestDI2 _TestDI2)
{
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 TestDIMyClass ");
var t2 = this._TestDI2 ;
if(t2 == null) throw new ArgumentException(" service TestDI2 is null in TestDIMyClass ");
return TestMyFunc1(t1,t2,x,y);
}
}//class
}//namespace
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/RSCG_FunctionsWithDI
Leave a Reply