Reputation: 561
For my application I'm trying to write a configuration controller, to load and save settings for certain modules. To do this I am going to use an INI file, where the section names would represent the module names (or other identification), and the values represented by a key.
I registered my controller in the bootstrapper, and use the interface in my constructor for injection in the appropriate classes. However I do not want to enter the module name every time I need to get or set a value, so I tried to use Caller info to find out what module (or class) is calling the method, but this apparently does not work (return empty string).
Is there another way to achieve what I'm trying to do?
Bootstrapper:
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<IConfig, ConfigController>(new ContainerControlledLifetimeManager());
}
Config interface:
public interface IConfig
{
string[] GetSettings(string caller = "");
void Set<T>(string setting, T value, string caller = "") where T : class;
T Get<T>(string setting, string caller = "") where T : class;
}
Upvotes: 1
Views: 1309
Reputation: 17367
The use of caller argument is error prone. You have many options to avoid it:
Register a ConfigController for each module. Unity supports multiple named registration. You can inject the right controller in each module in the module initialization, or with a Dependency
attribute:
Container.Register<IConfig, ConfigController>("module1",
new InjectionConstructor("module1"))
.Register<IConfig, ConfigController>("module2",
new InjectionConstructor("module2"));
class Module1 {
public Module1([Dependency("module1")] IConfig config) {... }
}
Define and implement a IConfigFactory that returns a configured IConfig implementation.
interface IConfigFactory {
IConfig Create(String moduleName);
}
The ConfigController could identify the module detecting the method the made the call.
Upvotes: 1