I need to access my database in the Singleton class created in my Startup class. It seems that the injection directly leads to the placement of the DbContext.
I get the following error:
Unable to access the remote object. Object Name: "MyDbContext".
My question is twofold: why does this not work and how can I access my database in an instance of the singleton class?
Here is my ConfigureServices method in my Startup class:
public void ConfigureServices(IServiceCollection services) { // code removed for brevity services.AddEntityFramework().AddSqlServer().AddDbContext<MyDbContext>( options => { var config = Configuration["Data:DefaultConnection:ConnectionString"]; options.UseSqlServer(config); }); // code removed for brevity services.AddSingleton<FunClass>(); }
Here is my controller class:
public class TestController : Controller { private FunClass _fun; public TestController(FunClass fun) { _fun = fun; } public List<string> Index() { return _fun.GetUsers(); } }
Here is my FunClass:
public class FunClass { private MyDbContext db; public FunClass(MyDbContext ctx) { db = ctx; } public List<string> GetUsers() { var lst = db.Users.Select(c=>c.UserName).ToList(); return lst; } }
c # dependency-injection asp.net-core
Tjaart
source share