I'm working on project who has a lot of common repeated functions in differents razor components doing same work. Like this.
void TrySelect(clsCity item)
{
_isOpen = false;
SelectedText = item.Nombre;
SelectedValue = item.ID;
objSearchHotel.SearchObject = item;
this.StateHasChanged();
}
This function (and others) are used at least in 26 files. Im new into a pattern designs, it's possible to create a file as service and consume/inject that service with this "common functions" in every razor component that i need? Something like repository pattern?
i'm new on pattern designs, still learning and i can't understand at all
So, I would not suggest creating a base class
and then inherit its funcionalities. If doing so, it should be an interface
at least.
The best way to solve your issue from my point of view —- is to create a service too. You could create an app-scoped service that you can inject in any class you need.
I hope it helps you!
I will try to give an example of how it works in the form of your own codes.
Firstly, you should create an interface as follows:
public interface IFoo
{
public clsCity GetItem();
}
Now, you should create a service and inherit from above interface:
public class FooService:IFoo
{
public clsCity GetItem()
{
return clsCity;
}
}
You should register the interface and service in the startup as follows:
Services.AddScoped<IFoo,FooService>();
Finally, You can inject the FooService in any components as follows:
@inherits OwningComponentBase<IFoo>
.
.
<EditForm Model="clsCityModel">
<InputSelect @bind-Value=clsCityModel.Id>
clsCityModel.Nombre
</InputSelect>
</EditForm>
.
.
@code
{
private IFoo fooService => Service;
private clsCity clsCityModel = new clsCity();
protected override void OnInitialized()
{
base.OnInitialized();
TrySelect();
}
void TrySelect()
{
_isOpen = false;
clsCity clsCityModel = FooService.GetItem();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.