0

I am injecting in my services a global Settings interface, as Singleton, using StructureMap:

public interface ISettings {
  LoggerSettings Logger { get; }
} // ISettings

public class LoggerSettings {
  public String Levels { get { return ConfigurationManager.AppSettings["Logger.Levels"]; } }
  public const String Report = "team@xyz.com";
} // LoggerSettings

public class Settings : ISettings {
  public LoggerSettings Logger { get; private set; }
} // Settings

And as SM configuration I have:

For<ISettings>().Singleton().Use<Settings>();

I am able to inject this object but when I check the injected object its property Logger is null ... How can I have SM to initialize the object properties?

Am I missing something?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

1

You need a constructor on the Settings class that has a LoggerSettings parameter so that StructureMap can set the Logger property on creation.

If you for some reason can't/don't want to use Constructor injection you need to make the setter on the Logger property on the Settings class public and configure property injection in StructureMap.

TL;DR: make Settings look like this:

public class Settings : ISettings {
    public Settings(LoggerSettings logger)
    {
         Logger = logger;
    }

    public LoggerSettings Logger { get; private set; }
} 
Community
  • 1
  • 1
PHeiberg
  • 29,411
  • 6
  • 59
  • 81
  • Don't I need to have a ILoggerSettings and a LoggerSettings? – Miguel Moura Mar 28 '13 at 12:07
  • No, it should work without an interface. StructureMap will create instances of concrete classes as long as it can resolve all the dependencies. If you wish to be able to change the implementation of the LoggerSettings (for testability, etc) you need an interface though or make the properties settable. – PHeiberg Mar 28 '13 at 12:12