Search code examples
c#dryioc

Update an already injected service DryIoc c#


Hi I have a situation where I need to update a service that I have injected.

When I first launch the app I have something like

public class MyService:IMyService
{
  public string ValueAPopulatedBeforeLogin { get; set; }
  public string ValueBPopulatedBeforeLogin { get; set; }
  public string ValueCPopulatedAfterLogin { get; set; }
 }
container<IMyService,MyService>();
  1. Start the app
  2. ValueA and B are populated ValueC IS NOT
  3. Login now valueC is populated

Now I need to update MyService but doing

 container.ClearCache(typeOf(IMyService));
 container.UseInstance(MyService);  //with new ValueC updated value

however the new property has not been updated.

How do you update an already injected service? Is this possible?

thanks

Update

  1. I launch the app and IMyService is registed in the container
  2. The "MyService" implementation has been invoked. (I guess the fact that has been invoked is key here)
  3. Now any injected services have some values populated
  4. I logged on and I get additional values and I would like to replaces all services inside my container
  5. I apply the "IfAlreadyRegister" syntax you suggested and If I resolve it again all the new additional properties are there.
  6. But when I go the service again the already injected services have not changed!!
  7. However if I resolve it again they are there..

Which leads to a conclusion and hopefully I am wrong - I cannot change the already injected services (constructor) but I would need to resolve them again.

Hope its clear enough to understand what I want to do


Solution

  • It is not clear from the question, because the code sample is incomplete. But probably, just probably, you need something like:

    container.ClearCache(typeOf(IMyService));
    container.RegisterInstance<IMyService>(
        new MyService { ValueCPopulatedAfterLogin  = "blah" }, 
        ifAlreadyRegister: IfAlreadyRegister.Replace);