Reputation: 23749
In an ASP.NET Core 1.0 project, using DI how can I pass parameters to constructor. For instance, how do I register the following service in Startup.cs. services.AddTransient(typeof(IStateService), new StateService());
does not work since StateService() requires an input parameter of type BlogingContext. Or, are there alternative way of building the following service with database involved? Here State
is a table coming from SQL Server Db. App is using EntityFrameworkCore
with Code First approach. I'm using latest release of ASP.NET Core 1.0 and VS2015-Update 3 released on June 27, 2016
I see a similar example here but not quite the same type of input parameter.
Service:
public interface IStateService
{
IEnumerable<State> List();
}
public class StateService : IStateService
{
private BloggingContext _context;
public StateService(BloggingContext context)
{
_context = context;
}
public IEnumerable<State> List()
{
return _context.States.ToList();
}
}
Upvotes: 3
Views: 1543
Reputation: 2275
As documentation states here (Scroll a bit down) you should register the IStateService
and BloggingContext
like:
services.AddDbContext<BloggingContext>();
services.AddScoped<IStateService, StateService>();
Then DI will resolve the whole dependency tree for you. Note that you should use scoped lifetime on service, because the service should use same lifetime as DbContext and it uses scoped.
Upvotes: 2