开发者

Updating an instance registered with Unity container

开发者 https://www.devze.com 2023-03-19 08:40 出处:网络
I am using Unity for dependency injection and have the instance of a class Config that implements IConfig registered with the Unity Container.

I am using Unity for dependency injection and have the instance of a class Config that implements IConfig registered with the Unity Container.

IConfiguration config = new Configuration();

unityContainer.RegisterInstance<IConfiguration>(config);

When the app is running and the user loads a saved configuration, I wo开发者_开发知识库uld like to update the instance stored in Unity with the configuration object loaded. E.g. something like the psuedo code below

IConfiguration loadedConfig = FileLoadService.Load(filepath);
unityContainer.Instance = loadedConfig;

Is this possible?


You could just re-register the instance by calling

unityContainer.RegisterInstance<IConfiguration>(config);

But a better solution would be to change your FileLoadServce.Load(filepath) logic so that it updates the values of your existing configuration object. The benefit of this solution would be that already resolved references (by calling unityContainer.Resolve<IConfiguration>()) to this config object are updated, too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号