.NET Core 2 - Call Repository method from Startup
Solution 1
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.
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.
For .NetCore 2 dependency injection, click the MSDN Link for more details.
Solution 2
Could be this article can help: https://medium.com/@mattmazzola/asp-net-core-injecting-custom-data-classes-into-startup-classs-constructor-and-configure-method-7cc146f00afb
Basically to inject some service to the startup, you need to call ConfigureServices
before calling UseStartup
in WebHostBuilder()
chain:
var host = new WebHostBuilder()
.ConfigureServices(servicesCollection =>
{
servicesCollection.AddSingleton<IValueService>(new ValueService(context));
})
.UseStartup<Startup>()
.Build();
Then your service would be resolved if injected to startup constructor:
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env, IValueService service)
{
//service.GetAll();
}
}
Comments
-
phicon almost 2 years
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 } }
In my Startup.cs;
services.AddScoped<IValueService, ValueService>();
How would i call the method GetAll() from Startup or from another Class?
EDIT: Answered in; .NET Core 2 - Create instance of controller class which has a repository
-
Dushan Perera about 6 yearsfrom another class ? Inject
IValueService
via constructor injection and use that. Take a look at Dependency injection in ASP.NET Core -
DavidG about 6 yearsThis is basially the same question you aked a few minutes ago stackoverflow.com/questions/48633396/…
-
Tiago B about 6 yearsThere is nothing wrong in this question to receive down votes. If so, please share your critic so the author can improve the question.
-
phicon about 6 years@DavidG yes, still the same problem - would be great if could point me in the right direction. To my understanding a controller gets called from the front-end. However, i just need to know how to call these methods without using a controller / front-end.
-
DavidG about 6 yearsYou've already been given a few links, it's now up to you to go and learn.
-
NonStatic about 6 years@phicon, you don't have to use controller to call a service. Service A could call Service B as well. Just follow the link I put in my answer and you will learn that.
-