简体   繁体   中英

C# LightInject - How to replace an instance in a contain with another

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM