Scoped Service needs to be injected into all services

1.2k Views Asked by At

I have a controller with a scoped service. IMyService

I also have a service ISecondaryService which requires this scoped service.

My controller sets a property MyProperty IMyService in the constructor

When I look ISecondaryService's constructor I need to have the same injected service.

However, MyProperty is null within ISecondaryService

What could cause this?

Im using .NET Core 3.1

public interface IMyService
{
   string MyProperty {get;set;}
}

public class MyService: IMyService
{
   public string MyProperty {get;set;}
}

public MyController
{
    public MyController(ISecondaryService secondaryService, 
                              IMyService myService): base( myService)
    {
       _myService = myService;
       myService.MyProperty = "Hello";  
    }
}

public SecondaryService: ISecondaryService
{
    public SecondaryService(IMyService myService)
    {
        _myService = myService;
    }
}

I need _myService.MyProperty to be Hello

In startup I have

services.AddScoped<IMyService, MyService>();
services.AddTransient<ISecondaryService, SecondaryService>();
        
        

Paul

1

There are 1 best solutions below

2
Cyril ANDRE On

program.cs

builder.Services.AddScoped<IMyService>(new MyService());
builder.Services.AddScoped<ISecondaryService>(sp =>
{
    var myService = sp.GetService<IMyService>();
    return new ISecondaryService(myService);
});

You need to register the 1st service then register the second one and injecting the first one in it. From there, if your controller expect ISecondaryService to be injected, it will also provide IMyService.