Table of Contents

Dependency Injection

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

First, you will need to add a reference to NCalc.DependencyInjection to your project. If you are using ASP.NET Core, no need to install a DI container. If you are in a Console App or older framework, you will need to set up a DI container, Microsoft.Extensions.DependencyInjection is a DI container for example.

dotnet add package NCalc.DependencyInjection

At your Program.cs simply:

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 for example create a custom parser using another library instead of Parlot and implement this interface.

Example:

services.AddNCalc()
        .WithLogicalExpressionFactory<MyCustomLogicalExpressionFactory>();

WithEvaluationService

Use this method to specify a custom implementation of IEvaluationService. The evaluation service is used to calculate the result of your expression after parsing.

Example:

services.AddNCalc()
        .WithEvaluationService<MyCustomEvaluationService>();

By configuring these services, you can customize the behavior of NCalc to suit your application's needs.