15

I'm registering a service as a singleton in .NET Core. Yet I'm seeing the constructor for the singleton called multiple times.

services.AddSingleton<DbAuthorizationOptions, ContextAuthorizationOptions>();

My context authorization options is just Dictionary of Entity Types to IValidators, The context authorization options are passed into the DBContext, to automatically run validations.

During the registration of my services, I also register dynamic Validators with my container registered in DI.

var useDynamicValidator = serviceOption.ValidatorOptions != null;
if(useDynamicValidator)
{
    //TODO: Extract this to before the register service no sense in building the provider each time
    //TODO: Make this cleaner don't be dependent on Authorization options
    var provider = services.BuildServiceProvider();
    var authOptions = provider.GetService<DbAuthorizationOptions>();
    var validator = BuildDynamicValidatorFactory(serviceOption).Invoke(provider, null);
    authOptions.ValidatorOptions.AddValidatorForSet(validator);
}

I notice that when I call GetService on the provider I receive a new singleton instead of the existing one. Does building the provider create a new container so all of the services get re-registered?

If so, How can I call a method to register my dynamic validators in the singleton container with the existing IServiceProvider, is there a way to invoke some registration once after the service container is built?

2 Answers 2

6

Does building the provider create a new container so all of the services get reregistered?

Yes. See the source code.

If so, How can I call a method to register my dynamic validators in the singleton container with the existing IServiceProvider, is there a way to invoke some registration once after the servicecontainer is built?

I'm not really understanding why this is a problem. You should be registering all of your services one time at application startup in the Composition Root.

The DI container is then responsible for resolving the object graphs of the application. The application itself shouldn't have a dependency on it, nor be required to update it.

You should be injecting DbAuthorizationOptions in the place where you need to use it.

public class Foo : IFoo
{
    private readonly DbAuthorizationOptions authOptions;

    public Foo(DbAuthorizationOptions authOptions) // <-- Inject parameters
    {
        this.authOptions = authOptions ??
            throw new ArgumentNullException(nameof(authOptions));
    }

    public void DoSomething()
    {
        // TODO: Inject the type that has the BuildDynamicValidatorFactory
        // method and the serviceOption (whatever type that is) here
        // either as a method parameter of this method, or a constructor
        // parameter of this class.
        var validator = BuildDynamicValidatorFactory(serviceOption).Invoke(provider, null);
        // Now we have an instance of authOptions that can be used
        authOptions.ValidatorOptions.AddValidatorForSet(validator);
    }
}

Note that the DI container automatically provides the DbAuthorizationOptions if injected into another type that is also resolved through DI (such as a controller or filter).

NOTE: It isn't very clear from your question where you need to do this. You mention that you want it to happen once, which usually means to put it at application startup. But users cannot interact with code that runs at startup. So, maybe you could use a filter. It really all depends on where in the lifecycle of the application it has to happen.

6
  • I have a component which is dependent on having access to all of the Validators for any Entity in a context. I register a singleton a dictionary of EntityTypes to Validator. When the use registers with service factory, If there is not a concrete validator declare, the user can provide options passed to my service to create a dynamic validator. This dynamic validator needs to be registered with the singleton so the context has access to all the validators. So I need to register my dynamic validators once after the service container is built, How can I do this?
    – johnny 5
    Feb 18, 2018 at 21:15
  • See my edit. If you inject authOptions and it is a singleton, you should be able to access it in any service. So, at runtime you can build the factory and add the validation. I am not exactly sure where serviceOption comes from, so you will either need to inject it through the constructor or pass it as a method parameter. If it doesn't make sense, you should probably edit the question to provide some more context as to what your setup is like (or better yet, since this seems to be an XY problem, ask a new question). Feb 18, 2018 at 21:22
  • 1
    @johnny5 ... NightOwl888's factory pattern is the right approach, but to directly answer your question, the .NET Core DI container doesn't support adding services later on. My earlier answer about injecting IServiceProvider would fix your not-a-singleton problem, but it's the "service locator" anti-pattern which you generally want to avoid.
    – McGuireV10
    Feb 18, 2018 at 21:25
  • @NightOwl888 I'm not sure if this will work with my implementation but it hard to explain my full problem with out dumping pages of code here. I'll investigate both solutions to see which will work better
    – johnny 5
    Feb 18, 2018 at 21:44
  • @NightOwl888 thanks I ended up using a modified version of this
    – johnny 5
    Feb 18, 2018 at 23:46
0

You can declare a dependency on IServiceProvider -- don't build it, inject it.

public class SomeController
{
    DbAuthorizationOptions authOptions;
    public SomeController(IServiceProvider provider)
    {
        authOptions = provider.GetSerivce<DbAuthorizationOptions>();
    }
}

But this is the service locator anti-pattern. As I commented on NightOwl888's post after you gave more details, a factory is probably a better approach.

3
  • what do you mean don't build it just inject it? how can I inject it?
    – johnny 5
    Feb 18, 2018 at 21:27
  • Interesting I'll need to investigate whether in my case it's possible to use the factory approach, this should work though
    – johnny 5
    Feb 18, 2018 at 21:39
  • Actually, there is no factory in the solution I gave (beyond the one I copied and pasted). My solution injects the DbAuthorizationOptions. This solution resolves the DbAuthorizationOptions using a service locator. It looks the same on paper, but the difference is that when you inject IServiceProvider you are tightly coupling the code to IServiceProvider so it cannot live without this extra interface. If you want to swap out DbAuthorizationOptions for another implementation or a mock, you have more hoops to jump through using the service locator approach. Feb 18, 2018 at 21:47

Your Answer

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

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