Dependency Injection
Dependency Injection is not available in the AOT version.
Introduction to Dependency Injection (DI)
Dependency Injection (DI) is a design pattern used to implement Inversion of Control (IoC) between classes and their dependencies. It allows the creation of dependent objects outside a class and provides those objects to the class in various ways. This leads to more flexible, reusable, and testable code. For more information on Dependency Injection, refer to the Microsoft documentation.
Installation and Usage
In Allied Bits NCalc, dependency injection support is included in the same package and assembly as the regular ones. If you are using ASP.NET Core, there is no need to install a DI container. If you are have a Console App or an older framework, you will need to set up a DI container. Microsoft.Extensions.DependencyInjection is an example of a DI container.
dotnet add package NCalc
In your Program.cs, add:
builder.Services.AddNCalc();
builder.Services.AddTransient<MyService>(); // This is just an example.
You will need to use IExpressionFactory to create expressions with injected services.
using NCalc.Factories
public class MyService(IExpressionFactory expressionFactory)
{
public object? EvaluateExpression(string expressionString)
{
var expression = expressionFactory.Create(expression, ExpressionOptions.DecimalAsDefault);
return expression.Evaluate(expressionString);
}
}
Methods
See NCalcServiceBuilder to see all methods.
WithExpressionFactory
Use this method to specify a custom implementation of IExpressionFactory. This factory is responsible for creating Expression objets that NCalc will evaluate. You can for example create a custom implementation with an object pool to re-use expression objects.
WithCache
Use this method to specify a custom implementation of ILogicalExpressionCache. This cache is used to store and retrieve parsed LogicalExpression objects.
Example:
services.AddNCalc()
.WithCache<MyCustomCache>();
WithLogicalExpressionFactory
Use this method to specify a custom implementation of ILogicalExpressionFactory. This factory is responsible for creating LogicalExpression objects. These objects represent a parsed string into an expression. You can create a custom parser using another library instead of Parlot and implement this interface.
Example:
services.AddNCalc()
.WithLogicalExpressionFactory<MyCustomLogicalExpressionFactory>();
WithEvaluationVisitorFactory
Use this method to specify a custom implementation of IEvaluationVisitorFactory. The created evaluation visitor is used to calculate the result of your expression after parsing.
Example:
services.AddNCalc()
.WithEvaluationVisitorFactory<MyCustomEvaluationVisitorFactory>();
By configuring these services, you can customize the behavior of NCalc to suit your application's needs.