1

New to Simple Injector, trying to get some pieces working for a prototype. I am creating a WPF application that uses Simple Injector and ReactiveUI, but can't seem to get explicit property injection via attribute to trigger. The specific example I am working through is just testing injection of a logger. The plan is to roll this into a decorator, but I have run across the need for attribute injection with previous projects/DI libraries. Just want to verify I am able to use it.

Snippet of the bootstrapping:

private Container RegisterDependencies(Container container = null)
{
    container ??= new Container();

    // Container initialization that must precede dependency registration
    // occurs here

    // Enable property injection via the [Import] attribute
    container.Options.PropertySelectionBehavior =
        new ImportPropertySelectionBehavior();

    SimpleInjectorInitializer initializer = new SimpleInjectorInitializer();
    Locator.SetLocator(initializer);

    Locator.CurrentMutable.InitializeSplat();
    Locator.CurrentMutable.InitializeReactiveUI();

    container.UseSimpleInjectorDependencyResolver(initializer);

    container.RegisterConditional(
        typeof(ILogger),
        c => typeof(NLogLogger<>)
            .MakeGenericType(c.Consumer.ImplementationType),
        Lifestyle.Singleton,
        c => true);
        
    container.Register<MainWindow>();

    container.Register<ISystem, System>(Lifestyle.Singleton);
            
    container.Verify();
    return container;
}

An instance of the System is requested from the DI container in the static RunApplication called from Main:

var system = container.GetInstance<ISystem>();

And here is the property injection in the system:

public class System : ISystem
{
    [Import] public ILogger Logger { get; set; }

    public System()
    {
        // Logger is null here. NullReferenceException is thrown
        Logger.LogInfo("Creating System");
    }
}

At this point in the constructor, the Logger property is null and attempt to log fails with exception. I should mention the ILogger is my own abstraction of NLog. If I instead perform constructor injection:

public System(ILogger logger)

Simple Injector picks up on this and resolves the dependency fine. I have tried changing the Import attribute to a different custom-defined Dependency attribute, no change. Have also tried just instantiating the logger as a singleton, same behavior.

Really appreciate any ideas, I'm running dry on searching forums, the SimpleInjector/ReactiveUI docs, and Steven's DI book.

Edit - here is the PropertySelectionBehavior code as well:

public class PropertySelectionBehavior<T> : IPropertySelectionBehavior
    where T : Attribute
{
    public bool SelectProperty(
        Type implementationType, PropertyInfo propertyInfo) =>
        propertyInfo.GetCustomAttributes(typeof(T)).Any();
}

public class ImportPropertySelectionBehavior : 
    PropertySelectionBehavior<ImportAttribute> { }

2nd Edit - I can take out all of the initialization related to ReactiveUI and still reproduce same behavior. New sample looks like:

private Container RegisterDependencies(Container container = null)
{
    container ??= new Container();

    container.Options.PropertySelectionBehavior =
        new ImportPropertySelectionBehavior();

    // Logger registration
    container.RegisterConditional(
        typeof(ILogger),
        c => typeof(NLogLogger<>)
            .MakeGenericType(c.Consumer.ImplementationType),
        Lifestyle.Singleton,
        c => true);

    // UI registration
    container.Register<MainWindow>();
    //container.Register<MainWindowViewModel>();

    container.Register<ISystem, System>(Lifestyle.Singleton);

    container.Verify();
    return container;
}

2 Answers 2

0

You are using the Logger property from inside System's constructor. Properties, however, are only initialized after the constructor finished. If you remove Simple Injector from the equation, and fallback to plain old C#, you would see the same. For instance:

var system = new System() // <-- constructor call
{
    Logger = new NLogLogger<System>() // Logger_set is called after the ctor
};

If you run this code, you will see the same NullReferenceException thrown by the constructor of System.

What this means is that you shouldn't use any properties from inside your constructor. Even more broadly, from a DI perspective, you shouldn't use any service inside your constructor (or during construction for that matter) as is described by Mark Seemann here.

0

Update, the explicit property injection is working fine. It occurs after construction. I imagine there are design reasons for this, although somehow it was contrary to my mental model that the property injection would be performed on-demand/on first use.

Planning on experimenting a bit more to see what control is available over the timing to resolve property dependencies. If anyone who is more experienced has any advice on that or can point me to additional documentation I would welcome it. The decorator sounds like the more elegant way to make sure the logger is available as expected and allow independent lazy loading of decoratee concerns. Some discussion here:

SimpleInjector - "Lazy" Instantiate a singleton that has dependencies on first use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.