[英]Multiple "common functions" repeated in different razor component
I'm working on project who has a lot of common repeated functions in differents razor components doing same work.我正在从事一个项目,该项目在不同的 razor 组件中有很多重复的功能,做同样的工作。 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.这个 function(和其他)至少在 26 个文件中使用。 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?
我是模式设计的新手,可以创建一个文件作为服务,并在我需要的每个 razor 组件中使用这个“通用功能”使用/注入该服务吗? 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.所以,我不建议创建一个基础
class
然后继承它的功能。 If doing so, it should be an interface
at least.如果这样做,它至少应该是一个
interface
。
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.
您可以创建一个应用范围的服务,您可以将其注入到您需要的任何 class 中。
Useful link with instructions 有用的说明链接
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:最后,您可以在任何组件中注入 FooService,如下所示:
@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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.