i am creating a Nuget Package should supports the dependency injection (DI) throw a service called "IGETSum" with one method called "SUMorSUB" that’s take a two numbers and sum them or subtract them. every thing is done except call the method in program.cs, calling the method in program.cs should contains options and be like :
builder.Services.SUMorSUB(opt => opt.operation = "+");
the option "operation" will specify which operation will be done. either SUM(+) or SUB(-).
below is the package code
using System;
namespace IGETSum
{
public class SumNuget
{
public string operation;
public int SUMorSUB(int num1,int num2) {
var res=0;
if (operation == "+")
{
res= num1+ num2;
}
else
{
res = num1 - num2;
}
return 0;
}
}
}
the main reason of this question is to know how to make the nuget support Dependency Injection (DI) and to know how to add options. any help is highly appreciated.
There are different ways consumers of your library can register your service for use in their application. The way you've likely consumed other libraries that integrate with DI is by calling an extension method provided for
IServiceCollection.For example, here's an extension method to register your
SumNugetclass:Which can then be invoked as:
To go a bit further and provide a way to configure the options for your service, there are a couple different ways you can go. I would suggest reading the configuration documentation, and suggest implementing the behaviour with the "options pattern".
The following I'm typing without running at all - so I recommend reading the above documentation rather than the code I'm writing on the fly in Stack Overflow's editor. I make no guarantees on its correctness
We change
SumNugetto haveIOptions<SumNugetOptions>injected, which it uses to determine its behaviour:You can imagine some
SumNugetOptionsobject with a string typeoperationproperty on it.Then in your extension method:
Hopefully the above gives you some direction on how this can be achieved.
P.S. You might want to return
resrather than0inSUMorSUB