ASP.NET Core Dependency Injection, inject with parameters

asp.net-core c# dependency-injection entity-framework-core visual-studio-2015

Question

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();
         }
     }
1
3
7/4/2018 11:08:35 AM

Accepted Answer

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.

2
7/4/2016 3:07:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow