Question

Using SimpleInjector, I am trying to register an entity that depends on values retrieved from another registered entity. For example:

Settings - Reads settings values that indicate the type of SomeOtherService the app needs.

SomeOtherService - Relies on a value from Settings to be instantiated (and therefore registered).

Some DI containers allow registering an object after resolution of another object. So you could do something like the pseudo code below:

    container.Register<ISettings, Settings>();

    var settings = container.Resolve<ISettings>();

    System.Type theTypeWeWantToRegister = Type.GetType(settings.GetTheISomeOtherServiceType());

    container.Register(ISomeOtherService, theTypeWeWantToRegister);

SimpleInjector does not allow registration after resolution. Is there some mechanism in SimpleInjector that allows the same architecture?

Was it helpful?

Solution

A simple way to get this requirement is to register all of the available types that may be required and have the configuration ensure that the container returns the correct type at run time ... it's not so easy to explain in English so let me demonstrate.

You can have multiple implementations of an interface but at runtime you want one of them, and the one you want is governed by a setting in a text file - a string. Here are the test classes.

public interface IOneOfMany { }
public class OneOfMany1 : IOneOfMany { }
public class OneOfMany2 : IOneOfMany { }

public class GoodSettings : ISettings
{
    public string IWantThisOnePlease
    {
        get { return "OneOfMany2"; }
    }
}

So let's go ahead and register them all:

private Container ContainerFactory()
{
    var container = new Container();

    container.Register<ISettings, GoodSettings>();
    container.RegisterAll<IOneOfMany>(this.GetAllOfThem(container));
    container.Register<IOneOfMany>(() => this.GetTheOneIWant(container));

    return container;
}

private IEnumerable<Type> GetAllOfThem(Container container)
{
    var types = OpenGenericBatchRegistrationExtensions
        .GetTypesToRegister(
            container,
            typeof(IOneOfMany),
            AccessibilityOption.AllTypes,
            typeof(IOneOfMany).Assembly);

    return types;
}

The magic happens in the call to GetTheOneIWant - this is a delegate and will not get called until after the Container configuration has completed - here's the logic for the delegate:

private IOneOfMany GetTheOneIWant(Container container)
{
    var settings = container.GetInstance<ISettings>();
    var result = container
        .GetAllInstances<IOneOfMany>()
        .SingleOrDefault(i => i.GetType().Name == settings.IWantThisOnePlease);

    return result;
}

A simple test will confirm it works as expected:

[Test]
public void Container_RegisterAll_ReturnsTheOneSpecifiedByTheSettings()
{
    var container = this.ContainerFactory();

    var result = container.GetInstance<IOneOfMany>();

    Assert.That(result, Is.Not.Null);
}

OTHER TIPS

As you already stated, Simple Injector does not allow mixing registration and resolving instances. When the first type is resolved from the container, the container is locked for further changes. When a call to one of the registration methods is made after that, the container will throw an exception. This design is chosen to force the user to strictly separate the two phases, and prevents all kinds of nasty concurrency issues that can easily come otherwise. This lock down however also allows performance optimizations that make Simple Injector the fastest in the field.

This does however mean that you sometimes need to think a little bit different about doing your registrations. In most cases however, the solution is rather simple.

In your example for instance, the problem would simply be solved by letting the ISomeOtherService implementation have a constructor argument of type ISettings. This would allow the settings instance to be injected into that type when it is resolved:

container.Register<ISettings, Settings>();
container.Register<ISomeOtherService, SomeOtherService>();

// Example
public class SomeOtherService : ISomeOtherService {
    public SomeOtherService(ISettings settings) { ... }
}

Another solution is to register a delegate:

container.Register<ISettings, Settings>();
container.Register<ISomeOtherService>(() => new SomeOtherService(
    container.GetInstance<ISettings>().Value));

Notice how container.GetInstance<ISettings>() is still called here, but it is embedded in the registered Func<ISomeOtherService> delegate. This will keep the registration and resolving separated.

Another option is to prevent having a large application Settings class in the first place. I experienced in the past that those classes tend to change quite often and can complicate your code because many classes will depend on that class/abstraction, but every class uses different properties. This is an indication of a Interface Segregation Principle violation.

Instead, you can also inject configuration values directly into classes that require it:

var conString = ConfigurationManager.ConnectionStrings["Billing"].ConnectionString;

container.Register<IConnectionFactory>(() => new SqlConnectionFactory(conString));

In the last few application's I built, I still had some sort of Settings class, but this class was internal to my Composition Root and was not injected itself, but only the configuration values it held where injected. It looked like this:

string connString = ConfigurationManager.ConnectionStrings["App"].ConnectionString;

var settings = new AppConfigurationSettings(
    scopedLifestyle: new WcfOperationLifestyle(),
    connectionString: connString,
    sidToRoleMapping: CreateSidToRoleMapping(),
    projectDirectories: ConfigurationManager.AppSettings.GetOrThrow("ProjectDirs"),
    applicationAssemblies:
        BuildManager.GetReferencedAssemblies().OfType<Assembly>().ToArray());

var container = new Container();

var connectionFactory = new ConnectionFactory(settings.ConnectionString);
container.RegisterSingle<IConnectionFactory>(connectionFactory);
container.RegisterSingle<ITimeProvider, SystemClockTimeProvider>();
container.Register<IUserContext>(
    () => new WcfUserContext(settings.SidToRoleMapping), settings.ScopedLifestyle);

UPDATE

About your update, if I understand correctly, you want to allow the registered type to change based on a configuration value. A simple way to do this is as follows:

var settings = new Settings();

container.RegisterSingle<ISettings>(settings);

Type theTypeWeWantToRegister = Type.GetType(settings.GetTheISomeOtherServiceType());

container.Register(typeof(ISomeOtherService), theTypeWeWantToRegister);

But please still consider not registering the Settings file at all.

Also note though that it's highly unusual to need that much flexibility that the type name must be placed in the configuration file. Usually the only time you need this is when you have a dynamic plugin model where a plugin assembly can be added to the application, without the application to change.

In most cases however, you have a fixed set of implementations that are already known at compile time. Take for instance a fake IMailSender that is used in your acceptance and staging environment and the real SmptMailSender that is used in production. Since both implementations are included during compilation, allowing to specify the complete fully qualified type name, just gives more options than you need, and means that there are more errors to make.

What you just need in that case however, is a boolean switch. Something like

<add key="IsProduction" value="true" />

And in your code, you can do this:

container.Register(typeof(IMailSender),
    settings.IsProduction ? typeof(SmtpMailSender) : typeof(FakeMailSender));

This allows this configuration to have compile-time support (when the names change, the configuration still works) and it keeps the configuration file simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top