1

Suppose I have ClassA and ClassB inherit from IClass. Now I have a LightInject container and register an instance of ClassA as

ClassA classA = new ClassA();
Helpers.Container.RegisterInstance(typeof(IClass), classA, "Class");

Now I want to replace classA with classB as

ClassB classB = new ClassB();
Helpers.Container.RegisterInstance(typeof(IClass), classB, "Class");

so that when I try to get an instance in another class can get classB rather than classA

(IClass) Helpers.Container.TryGetInstance(typeof(IClass), "Class");

However, I always get classA when I try to get an instance. How can I solve this problem? Thank you.

Update:

I have an IF statement to control which instance I want to register, such as

if (name == "classA")
{
    ClassA classA = new ClassA();
    Helpers.Container.RegisterInstance(typeof(IClass), classA, "Class");
}
else
{
    ClassB classB = new ClassB();
    Helpers.Container.RegisterInstance(typeof(IClass), classB, "Class");
}

In my code, the first round, the condition will be true. Therefore, I will register classA to the container. The second round, the condition will be false. As a result, I hope classB will be registered to the container. When I try to get the instance, I will get classA after the first round and then get classB in the second round. However, the current situation is that in both rounds, I get classA.

Ben
  • 957
  • 1
  • 11
  • 37
  • Did you comment out the `Helpers.Container.RegisterInstance(typeof(IClass), classA, "Class");` line? – mjwills Jun 17 '17 at 12:56
  • `if (true)` will always go into the first branch. what is the condition? – Nkosi Jun 17 '17 at 13:42
  • This is just an example. It can be any condition, such as if (name == "classA") – Ben Jun 17 '17 at 13:45
  • Did you try to remove instance from LifeTimeManager immediatly (in your case it is **ContainerControlledLifetimeManager**)? Retrive a registration `var registration = container.Registrations.FirstOrDefault(reg => /*reg.RegisteredType == typeof(IClass) &&*/ reg.LifetimeManagerType == typeof(ContainerControlledLifetimeManager) && reg.Name == "Class");` and then `registration.LifeTimeManager.RemoveValue(); registration.LifeTimeManager.SetValue(classB)`. – George Alexandria Jun 17 '17 at 21:41

1 Answers1

1

I am the author of LightInject.

Might be because you are trying to register a service after it has been resolved. Hard to say without a complete example. Create an issue in the LightInject repo with a link to small repro and we will help you out

seesharper
  • 3,249
  • 1
  • 19
  • 23