简体   繁体   中英

How can pass a data context to a static method in Asp .Net Core

I want to pass ApplicationContext to a static method. I tried many different ways, but nothing worked. I tried it without statics and much more, the context always returns null.

This is the original code I wrote, but it gives the errors "An object reference is required for the nonstatic field, method, or property"

public class SelectItemHelper
{
    private readonly ApplicationContext db;

    public SelectItemHelper(ApplicationContext context)
    {
        db = context;
    }

    public static IEnumerable<SelectListItem> GetDeveloper()
    {
        var developer = db.Games.ToList();

        IList<SelectListItem> items = new List<SelectListItem>();

        foreach (var dev in developer)
        {
            items.Add(new SelectListItem {Text = dev.Article, Value = dev.Article });
        }    
        return items;
    }
}
  • Remove the static keyword, hence making the method an instance member
  • Register your class as a service in the ConfigureServices : services.AddScoped<SelectItemHelper>(); .

Thus, you can simply inject your class: in a controller or a view (using @inject )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM