ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

TryAdd not seem to be respected #158

Closed stephenlautier closed 6 years ago

stephenlautier commented 6 years ago

I found a small thing, which I'm not entirely sure if its a bug or not;

// services.AddSingleton<IGrainActivator, TenantGrainActivator>(); // without this it doesnt work
var container = new DependencyInjectionContainer(c => c.Behaviors.AllowInstanceAndFactoryToReturnNull = true);
container.Configure(c =>
{
    c.Export<TenantGrainActivator>().As<IGrainActivator>().Lifestyle.Singleton(); // i had expected this would work equivalent to the above
    ...
});
var providers = container.Populate(services);

var ac = providers.GetService<IGrainActivator>(); // this doesnt give me TenantGrainActivator as I had expected 

return providers;

Instead its returning DefaultGrainActivator which that one is being registered by the Orleans via services.TryAddSingleton<IGrainActivator, DefaultGrainActivator>();, seems like either Populate is registering before (perhaps lazy?) or its not respecting the TryAddXXX

ipjohnson commented 6 years ago

@stephenlautier If I remember correctly the TryAddSingleton method is checking if the service is registered in services instance and registering it in the services instance when it's not found (I need to double check that). Try moving the container.Configure call below the Populate call and you should get the behavior you are looking for.

Just as an FYI Grace you can register many implementations the last one registered will win.

stephenlautier commented 6 years ago

Yes, TryAddSingleton thats how i know it as well.

As you suggested it hard worked as well :). I thought Populate had to be last since it returns the IServiceProvider, but even after reconfigure later it still work correctly. Thanks!

ipjohnson commented 6 years ago

The Populate call can be called at any point though I would recommend it be called first because then the registration are treated as the defaults and anything registered with the container after that will override what ever came from the services collection.

Can I close this out?

stephenlautier commented 6 years ago

Yes, thanks for your help and suggestion!