Sorush
Sorush

Reputation: 4129

In Blazor client, how to create a component for an interface?

From reusabilty point of view, I want to create a component for an interface. So I use it with different concrete objects.

For example, the interface is like this

interface ICalculation
    {
        double Calculate();
    }

and the Test component is

<button @onclick="(() => SetResult())">Set</button>
@result

@code{
double result;
ICalculation Calculation;
void SetResult()
{
result = Calculation.Calculate();
}

}

so some where else in another component/page I have some thing like this

<Test  inject CalculationA />
<Test  inject CalculationB />

So I want to inject Different Calculations into different instances of this component. How can i get this?

I thought using dependency injection of net core, but that is for to inject one object for an interface. Why important? It helps me to override requests to api, for example, admin and user have different requests but they see the same page structure.

Upvotes: 3

Views: 668

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

In the Test component you would make it a normal parameter:

[Parameter]  
public ICalculation Calculator { get; set; }

and then in 'some where else'

@inject CalculationA  CalculationA  
@inject CalculationB  CalculationB  

<Test  Calculator="CalculationA" />
<Test  Calculator="CalculationB" />

Or replace those '@inject` lines with normal instantiations (2x) because with multiple implementations you can't do DI on the interface anyway.

Upvotes: 3

Related Questions