0

How can I set the property of a service that is registered in ServiceCollection after it is constructed. I cannot pass the value to the constructor as it would result in circular dependency. Wanted behavior:

   public class ServiceA : IServiceA
   {
        public ServiceA(IServiceB serviceB)
        {
            ServiceB = serviceB;
        }
        IServiceB ServiceB {get; set;}
   }

   public class ServiceB : IServiceB
   {
       ServiceA {get; set;}
   }

   services.AddSingleton<IServiceA, ServiceA>();
   services.AddSingleton<IServiceB, ServiceB>();
   //I need something like this
   services.Inject<IServiceB>((serviceB, serviceProvider) => 
  {
      serviceB.ServiceA = serviceProvider.GetService<IServiceA>();
  });
M T
  • 968
  • 1
  • 8
  • 24

1 Answers1

0

Why call the constructor at all?

How about just:

public class ServiceB : IServiceB
{
    private readonly IServiceA _serviceA
    public ServiceB(IServiceA serviceA)
    {
         _serviceA = serviceA;
    }

    public IServiceA ServiceA {get { return _serviceA;}}
}

I don't see any circular reference here unless ServiceA needed ServiceB and you haven't demonstrated that. This is so far a linear setup.

Mark Fitzpatrick
  • 1,624
  • 1
  • 11
  • 8
  • Yes ServiceA should have a reference to ServiceB and vice versa. I will update the question to make it more clear. – M T Jun 19 '19 at 13:59
  • 1
    Then I hate to say it but I think there is a fundamental flaw with the design. If you have this kind of circular dependency then it's not something that would be good without Ioc and Ioc isn't going to solve this problem. It sounds like you need an IServiceC that takes in both to do very specific things as circular references are usually a good sign that there is a mis-identification of where the seams in the problem are. – Mark Fitzpatrick Jun 19 '19 at 14:56
  • There probably is but I want the answer regardless. Btw this happens because of situation described in here: https://softwareengineering.stackexchange.com/questions/393493/set-updatedby-reference-in-identitydbcontext-savechanges if you can suggest a better solution I will be grateful! – M T Jun 19 '19 at 15:36