SimpleInjector icon indicating copy to clipboard operation
SimpleInjector copied to clipboard

conditional resolution not providing instance created by factory delegate

Open zsvanderlaan opened this issue 9 years ago • 11 comments

Using the .NET Core application code below where Program is the entry point, I create and configure a container using the RegisterPackages extension method.

I have placed a breakpoint in each package to ensure all of my registrations are being added to the container. When I place a breakpoint inside the singleton delegate within the ApiWebHostBuilderPackage the breakpoint is also being hit, verifying the delegate is being invoked, but that the resulting instance returned by the delegate is not being provided as the implementation of the conditional registration.

I think the conditional is evaluated to determine the concrete type, but for some reason Simple Injector is not searching its registrations for one which matches the concrete type.

public class Program
{
    var container = new Container();
    container.Options.DefaultLifestyle = Lifestyle.Scoped;
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
    container.RegisterPackages(GetType().GetTypeInfo().Assembly);

    // Error is triggered here
    container.Verify();
}


public class IWebHostBuilderPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.RegisterConditional<IWebHostBuilder, ApiWebHostBuilder>(
            Lifestyle.Singleton, 
            cfg => typeof(ApiServer).IsAssignableFrom(cfg.Consumer.ImplementationType)
        );
    }
}

public class ApiWebHostBuilderPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.Register<ApiWebHostBuilder>(() =>
        {
            return (ApiWebHostBuilder)new ApiWebHostBuilder().UseKestrel()
                // I am specifying a startup type here. This should prevent the exception 
                // being thrown.
                .UseStartup<Startup>()
        }, Lifestyle.Singleton);
    }
}



public class ApiServer
{
    // builder has been verified to be of type ApiWebHostBuilder
    // provided instance of builder has been verified to not be configured and therefore 
    // cannot be the same instance as was configured by singleton delegate
    public ApiServer(IWebHostBuilder builder)
    {
        // Exception is thrown here
        builder.Build();
        // System.InvalidOperationException: // 'No service for type 
        // 'Microsoft.AspNetCore.Hosting.IStartup' has been registered.'
    }
}

public class ApiWebHostBuilder : WebHostBuilder { }

public class ApiServerPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.RegisterSingleton<ApiServer>();
    }
}

public class Startup
{
    public Startup(IHostingEnvironment environment) { }
    public void ConfigureServices(IServiceCollection services) { }
    public void Configure(IApplicationBuilder appBuilder, 
        IHostingEnvironment env, ILoggerFactory logger) { }
}

This the exception information.

System.InvalidOperationException: The configuration is invalid. Creating the instance for type ApiServer failed. No service for type 'Microsoft.AspNetCore.Hosting.IStartup' has been registered. ---> SimpleInjector.ActivationException: No service for type 'Microsoft.AspNetCore.Hosting.IStartup' has been registered. ---> System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Hosting.IStartup' has been registered.

at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Api.Web.Infrastructure.Startup.ApiServer..ctor(IWebHostBuilder builder) in C:\Api.Web\Infrastructure\Startup\ApiServer.cs:line 13
at lambda_method(Closure )
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.CreateInstanceWithNullCheck()
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.GetInterceptedInstance()
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.BuildExpression()
at SimpleInjector.InstanceProducer.BuildExpressionInternal()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at SimpleInjector.InstanceProducer.BuildExpression()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.BuildExpression()
at SimpleInjector.InstanceProducer.VerifyExpressionBuilding()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.VerifyExpressionBuilding()
at SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt()
at SimpleInjector.Container.VerifyInternal(Boolean suppressLifestyleMismatchVerification)
at SimpleInjector.Container.Verify(VerificationOption option)
at SimpleInjector.Container.Verify()
at Api.Web.Program.Main(String[] args) in C:\Api.Web\Program.cs:line 17

zsvanderlaan avatar Jun 20 '17 23:06 zsvanderlaan

I did also verify that if I include builder.UseStartup<Startup>() in the ApiServer constructor before calling builder.Build() I do not get the IStartup exception, further confirming that the already configured instance is not being provided.

Thanks for looking into this and the fast initial response time, I've followed your blog for a long time and appreciate the work you put in to ensure simple injector is such an amazing tool.

zsvanderlaan avatar Jun 21 '17 13:06 zsvanderlaan

Your Api.Web.Infrastructure.Startup.ApiServer..ctor(IWebHostBuilder builder) in C:\Api.Web\Infrastructure\Startup\ApiServer.cs:line 13 is calling into Microsoft.AspNetCore.Hosting.WebHostBuilder.Build(), which fails with:

System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Hosting.IStartup' has been registered.

In other words, its the ASP.NET Core configuration system that throws this exception stating that there is no IStartup class.

I'm not this familiar with what you are doing here, but it seems that you're doing your configuration in an incorrect order. What I find very peculiar is that you build that API system inside a delegate registered in Sinple Injector, while you would typically build up that config before you register Simple Injector, or at least make them unrelated.

That said, the error seems completely unrelated to the conditional registration.

I think the conditional is evaluated to determine the concrete type

Simple Injector will never determine a concrete type by executing a delegate. It only uses information that is available at build-time, such as a concrete type that is supplied using a generic method call.

Simple Injector will however, try to construct the type of the conditional registration when you call Verify because it does its best to verify as much of your configuration as it reasonably can.

dotnetjunkie avatar Jun 21 '17 14:06 dotnetjunkie

I'm sorry for the difficulty / confusion in demonstrating this problem, but I am certain the problem is that the instance generated from the ApiWebHostBuilderPackage delegate is not the same instance that is provided to the ApiServer constructor, despite being a singleton instance.

I will provide modified code shortly to confirm, and again, I appreciate you reviewing this.

zsvanderlaan avatar Jun 21 '17 15:06 zsvanderlaan

I have confirmed they are different instances located at different memory references and created a simpler example.

In the simpler example:

ApiServer => FooConsumer
IWebHostBuilder => IFoo
ApiWebHostBuilder => ConcreteFoo
public class Program
{
    var container = new Container();
    container.Options.DefaultLifestyle = Lifestyle.Scoped;
    container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
    container.RegisterPackages(GetType().GetTypeInfo().Assembly);

    // Error is triggered here while inside of FooConsumer Ctor
    container.Verify();
}

public class FooConsumer
{
    public FooConsumer(IFoo foo)
    {
        // assign this instance to the 'Actual' static property so we can compare it
        DoTheyMatch.Actual = (ConcreteFoo)foo;
        // exception triggered within Test()
        DoTheyMatch.Test();
    }
}

public static class DoTheyMatch
{
    public static ConcreteFoo Expected { get; set; }
    public static ConcreteFoo Actual { get; set; }

    public static bool Test()
    {
        if (Expected != Actual)
        {
            // this exception is thrown
            throw new Exception("References are different");
        }
        return true;
    }
}


public class FooConsumerPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.RegisterSingleton<FooConsumer>();
    }
}

public class IFooPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.RegisterConditional<IFoo, ConcereteFoo>(
            Lifestyle.Singleton
            , cfg => typeof(FooConsumer).IsAssignableFrom(cfg.Consumer.ImplementationType)
        );
    }
}

public class ConcreteFooPackage : IPackage
{
    public void RegisterServices(Container container)
    {
        container.Register<ConcreteFoo>(() =>
        {
            var foo = new ConcreteFoo();
            // assign this instance to the 'Expected' static property so we can compare it
            DoTheyMatch.Expected = foo;
            return foo
        }, Lifestyle.Singleton);
    }
}

public class ConcreteFoo : IFoo
{
}

public interface IFoo
{
}

here is the stack trace associated with the above code:

System.InvalidOperationException: The configuration is invalid. Creating the instance for type FooConsumer failed. References are different ---> SimpleInjector.ActivationException: References are different ---> System.Exception: References are different

at Api.Web.Infrastructure.DoTheyMatch.Test() in C:\Api.Web\Infrastructure\DoTheyMatch.cs:line 26
at Api.Web.Infrastructure.Startup.FooConsumer..ctor(IFoo foo) in C:\Api.Web\Infrastructure\Startup\FooConsumer.cs:line 14
at lambda_method(Closure )
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.CreateInstanceWithNullCheck()
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.GetInterceptedInstance()
at SimpleInjector.Lifestyles.SingletonLifestyle.SingletonLifestyleRegistration`1.BuildExpression()
at SimpleInjector.InstanceProducer.BuildExpressionInternal()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at SimpleInjector.InstanceProducer.BuildExpression()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.BuildExpression()
at SimpleInjector.InstanceProducer.VerifyExpressionBuilding()
--- End of inner exception stack trace ---
at SimpleInjector.InstanceProducer.VerifyExpressionBuilding()
at SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyThatAllExpressionsCanBeBuilt()
at SimpleInjector.Container.VerifyInternal(Boolean suppressLifestyleMismatchVerification)
at SimpleInjector.Container.Verify(VerificationOption option)
at SimpleInjector.Container.Verify()
at Api.Web.Program.Main(String[] args) in C:\Api.Web\Program.cs:line 17

zsvanderlaan avatar Jun 21 '17 16:06 zsvanderlaan

Your code can be simplified to the following to demonstrate the issue:

[TestMethod]
public void RegisterSameConcreteType_OneLambda_ReturnsSameInstance()
{
    var container = new Container();

    container.RegisterSingleton<IFoo, ConcreteFoo>();
    container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo());

    var expected = container.GetInstance<IFoo>();
    var actual = container.GetInstance<ConcreteFoo>();
    
    // this fails!
    Assert.AreEqual(expected,actual);
}

In v3 this was the expected behavior and would throw a TornLifestyleWarning. Because users frequently ran into this, Simple Injector v4 now merges multiple registrations which have

  1. The same lifestyle
  2. The same implementation type

That being said one would expect that the demonstrated unit test passes. The reason this test fails is because a lambda is being used to create the second registration.

So this test succeeds (while this would cause a TornLifestyle in v3).

[TestMethod]
public void RegisterSameConcreteType_TwoServiceTypes_ReturnsSameInstance()
{
    var container = new Container();

    container.RegisterSingleton<IFoo, ConcreteFoo>();
    container.RegisterSingleton<ConcreteFoo>();

    var expected = container.GetInstance<IFoo>();
    var actual = container.GetInstance<ConcreteFoo>();

    Assert.AreEqual(expected, actual);
}

We currently are discussing if the first unittest is a bug in the registration API. However it could be difficult to merge the registration in case a lambda is used. The reason merging could be difficult for lambda created instances, consider these registrations:

    container.RegisterSingleton<IFoo>(() => new ConcreteFoo());
    container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo());

In this case the container would never be able to determine which registration should be merged.

But if merging is not possible, there is still a bug or at a shortcoming in the diagnostic subsystem. The diagnostics should throw a TornLifestyleWarning so the user is at least warned and can take action accordingly.

To conclude, if it is possible for you to not use a lambda this would solve you're problem. If a lambda is the only way to go, you could do this:

// Create a single registration for creating `ConcreteFoo` by using a lambda
var registration = Lifestyle.Singleton.CreateRegistration(() => new ConcreteFoo(), container);

// Add the registration for both servicetypes
container.AddRegistration<ConcreteFoo>(registration);
container.RegisterConditional(typeof(IFoo), registration,
        cfg => typeof(FooConsumer).IsAssignableFrom(cfg.Consumer.ImplementationType));

This is however not really easy to do with the package setup you currently use. Do you actually need this?

TheBigRic avatar Jun 22 '17 19:06 TheBigRic

Yes, I need the package system to keep the cognitive load of our registrations low enough that our code is maintainable by any of the developers on my team.

Further, we have two separate projects which are each a microservice and provide a package to implement IFoo and they cannot be referenced by the IFoo package to create a common registration point.

The most common complaint I have heard using DI is that it obscures finding the source of a problem. We use packages located in the same file as the interface they are registering to minimize this indirection.

I would hope it would be possible to check the IFoo registration, see that it is supposed to return ConcreteFoo. From there, if a factory delegate exists for both IFoo and ConcreteFoo registrations I would expect a warning or exception, but if a factory delegate exists for ConcreteFoo but not for IFoo I would expect the ConcreteFoo delegate be invoked.

I believe this is a bug in the merging process, as i believe two registrations should only be merged when neither is using a lambda delegate.

I agree there should also be diagnostic warnings when multiple registrations exists with the same type, lifestyle, and use lambda delegates.

zsvanderlaan avatar Jun 23 '17 18:06 zsvanderlaan

but if a factory delegate exists for ConcreteFoo but not for IFoo I would expect the ConcreteFoo delegate be invoked

This means merging the registrations.

I believe this is a bug in the merging process, as i believe two registrations should only be merged when neither is using a lambda delegate.

Maybe I misunderstand you, but this statement seems to be contradictory. If you feel merging should only be done in case no lambda (factory delegate is probably a better term) is used for any of the involved registrations, the bug is currently nonexistent in the merging process. Because this already works as demonstrated in my second unit test.

If one of the registrations however does use a lambda (factory delegate) merging currently does not happen. And I believe this is not a bug, as you also state.

This should however indeed result in a warning IMO!

TheBigRic avatar Jun 23 '17 21:06 TheBigRic

I expect these tests to pass:

[TestMethod]
public void Test1()
{
    var container = new Container();

    container.RegisterSingleton<IFoo, ConcreteFoo>();
    container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo());
    
    container.Verify(VerificationOption.VerifyOnly);
    Assert.IsFalse(Analyzer.Analyze(container).OfType<TornLifestyleDiagnosticResult>().Any())

    var expected = container.GetInstance<IFoo>();
    var actual = container.GetInstance<ConcreteFoo>();
    Assert.AreEqual(expected,actual);
}

[TestMethod]
public void Test2()
{
    var container = new Container();

    container.RegisterSingleton<IFoo, ConcreteFoo>(() => new ConcreteFoo());
    container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo());

    container.Verify(VerificationOption.VerifyOnly);

    Assert.IsTrue(Analyzer.Analyze(container).OfType<TornLifestyleDiagnosticResult>().Any())
}

zsvanderlaan avatar Jun 28 '17 22:06 zsvanderlaan

For anyone interested, I have found the following workaround to accomplish what I need for the time being:

container.RegisterConditional(
    typeof(IFoo), 
    Lifestyle.Singleton.CreateRegistration(() => container.GetInstance<ConcreteFoo>(), container),
    c => typeof(ConcreteFooConsumer).IsAssignableFrom(c.Consumer.ImplementationType));

zsvanderlaan avatar Jun 28 '17 22:06 zsvanderlaan

Sorry for my absence in this conversation. I had a hard time wrapping my head around the conversation, considering I only had a smartphone to read the conversation, while at the same time I was sipping cocktails on the beach :)

I expect these tests to pass:

container.RegisterSingleton<IFoo, ConcreteFoo>(() => new ConcreteFoo());
container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo());

Let me start by saying that every change to the diagnostic system is a breaking change, so even if we find that such case should produce a warning, doing so typically means major version bump.

This particular example however is a bit tricky. When lambda registrations are used, diagnostics are to some extend disabled, because Simple Injector has no notion of what is happening inside the lambda. So to some extend Simple Injector trusts the user in knowing what he is doing.

For instance, the user might be doing the following:

container.RegisterSingleton<IFoo, ConcreteFoo>(() => new ConcreteFoo(value: 303));
container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo(value: 909));

Although a more realistic example would be:

var c3 = Lifestyle.Singleton.CreateRegistration(() => new ConcreteFoo(303), container));
var c9 = Lifestyle.Singleton.CreateRegistration(() => new ConcreteFoo(909), container));

In other words, in this case the user is explicitly specifying 2 ConcreteFoo instances (since it is impossible to create one instance with both the values 303 and 909). Because of this, Simple Injector will not merge both registrations, because that would mean that either one of the registrations is used, which obviously is incorrect.

The same would hold when having the following registration:

container.RegisterSingleton<IFoo, ConcreteFoo>();
container.RegisterSingleton<ConcreteFoo>(() => new ConcreteFoo(value: 909));

Here one registration uses Simple Injector’s auto-wiring facilities, while the other creates the instance by hand. Merging registrations would be an error, since Simple Injector has no idea whether the second registration has an identical constructor invocation as the first.

Although Simple Injector could obviously add a warning about this, this is quite tricky, since there are legitimate cases for this, such as the one we’ve seen previously:

var c3 = Lifestyle.Singleton.CreateRegistration(() => new ConcreteFoo(303), container));
var c9 = Lifestyle.Singleton.CreateRegistration(() => new ConcreteFoo(909), container));

A warning in Simple Injector is actually something that is much stronger than a warning: it is something that Simple Injector is quite sure about that it leads to incorrect behavior. See it as a C# warning, where your project is configured with “treat warnings as errors”. You can suppress a particular warning, but you don’t want to do this very often, because suppressing warnings is often confusing for users and leads to noise.

So I don’t have a final judgement on this issue. It would be nice if Simple Injector was able to push you into the right direction here, but we are at risk in complicating things for other users, while adding the warning is a breaking change.

Because of the complications that lambdas bring when it comes to Simple Injector's diagnostic system and the ability to help you in merging registrations, the typical advice is to minimize their use as much as possible.

dotnetjunkie avatar Jul 04 '17 15:07 dotnetjunkie

I need the package system to keep the cognitive load of our registrations low enough that our code is maintainable by any of the developers on my team.

Please note that the documentation explains that:

SimpleInjector.Packaging exists to accommodate applications that require plug-in like modularization, where parts of the application, packed with their own container registrations, can be independently compiled into a dll and ‘dropped’ into a folder, where the main application can pick them up, without the need for the main application to be recompiled and redeployed.*

In other words, packaging is only required when your application actually requires dynamic binding where concrete types are unknown at compile time and assemblies need to be loaded dynamically at runtime. As the documentation explains, you can still have modularization without packages by simply logically grouping registrations in methods without calling these registration groups using reflection. Here is the example from the documentation:

public void App_Start()
{
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    BusinessLayerBootstrapper.Bootstrap(container);
    PresentationLayerBootstrapper.Bootstrap(container);

    // add missing registrations here.

    container.Verify();
}

Advantage of using simple methods calls is that the behavior is deterministic compared to using dynamically loaded packages. When loading packages the order in which those packages are loaded is undeterministic, and this will be problematic if you have conditional registrations that are placed in different packages, since conditional registrations should be made in a strict order. Using simple method gives the same amount of componentization, while everything is visibly referenced from within the start-up path. In other words, you can use your IDE’s go-to reference feature to jump directly to that code, while still being able to group things together.

dotnetjunkie avatar Jul 04 '17 15:07 dotnetjunkie