.NET Core 2-启动中的调用存储库方法 [英] .NET Core 2 - Call Repository method from Startup

查看:117
本文介绍了.NET Core 2-启动中的调用存储库方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下存储库和类;

I have the following Repository and Class;

public interface IValueService
{
    GetAll();
}

public class ValueService : IValueService
{
    private DataContext _context;

    public ValueService(DataContext context)
    {
        _context = context;            
    }

    public GetAll()
    {
       // do something
    }
}

在我的Startup.cs中;

In my Startup.cs;

services.AddScoped<IValueService, ValueService>();

我如何从Startup或另一个Class中调用方法GetAll()?

How would i call the method GetAll() from Startup or from another Class?

编辑:已回答; .NET Core 2 -创建具有存储库的控制器类实例

推荐答案

调用 GetAll() ,无论在何处,都需要先拥有一个实例。因此,如果要在 Startup.cs 中调用它,则必须先创建一个对象,然后再调用它。

To call GetAll(), you need to have an instance first, no matter where. So if you want to call it in the Startup.cs, you have to create an object first and then call it.

要让其他类调用 GetAll(),您需要指定 IValueService 作为构造函数的参数之一,然后在构造函数中,将 IValueService 实例保留在本地私有属性中。此私有属性可以在同一类的其他方法中使用。

For other class to call the GetAll(), you need to specify IValueService as one of constructor's parameter, then in the constructor, you keep the IValueService instance in a local private property. This private property could be used in the other methods in the same class.

对于.NetCore 2依赖项注入,请单击 MSDN链接以获取更多详细信息。

For .NetCore 2 dependency injection, click the MSDN Link for more details.

这篇关于.NET Core 2-启动中的调用存储库方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆