3

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();
         }
     }
10
  • Have you tried registering BloggingContext with something like services.AddDbContext<BloggingContext>(); in startup? docs.asp.net/en/latest/fundamentals/… Commented Jul 3, 2016 at 23:33
  • @mollwe Thank you for trying to help. Your code would not register my custom service i.e. StateService Commented Jul 3, 2016 at 23:36
  • If you register state service as service.AddTransient<IStateService, StateService>();, will that make it work? Commented Jul 3, 2016 at 23:40
  • @mollwe But the StateService() constructor needs a parameter of type BloggingContext. Thtat's what VS complains. Commented Jul 4, 2016 at 0:10
  • 1
    There is a CharacterController with a ICharacterRepository with a ApplicationDbContext if you scroll down a bit. Even further down they register them for DI. ICharacterRepository matches your IStateService and ApplicationDbContext matches your BloggingContext... Commented Jul 4, 2016 at 2:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.