.NET Core 2 - 从 Startup 调用 Repository 方法 [英] .NET Core 2 - Call Repository method from Startup

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

问题描述

我有以下存储库和类;

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 或其他类调用 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 - 从 Startup 调用 Repository 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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