Search code examples
c#dependency-injectionasp.net-core-2.2

ASP.NET Core: DI Service with conditions


I want to register my service class ADManager in Startup. But the class have a string parameters in the constructor, and the instantiation depends if the user is on the same domain as the webb application.

// Constructor
public ADManager(
    string ADDomain, bool isSameDomain = true,
    string username = null, string password = null) 

Here is how I make a instance of the class manually, if is same domain:

var adManager = new ADManager(_authenticationSettings.AdDomain, _isSameDomain);

But if _isSameDomain equal false then it have to be created like this:

var adManager = new ADManager(
    _authenticationSettings.AdDomain, _isSameDomain, Input.Username, Input.Password);

Solution

  • You need to use the factory overload of AddScoped. The lambda you pass as the factory will be run each time the service is instantiated, which in a scoped lifetime, will be roughly every request.

    services.AddScoped<ADManager>(p =>
    {
        // use `p` to get any other services, i.e. `p.GetRequiredService<Foo>()`
        return new ADManager(...);
    });
    

    Just be aware, that while in normal operation, there should always be an associated request, it will be possible to, depending on how you use the service, that it will be operating outside the request pipeline. For example, if you attempted to pull it out in a singleton:

    using (var scope = _serviceProvider.CreateScope())
    {
        var adManager = scope.ServiceProvider.GetRequiredService<ADManager>();
        // HttpContext could be null in this scope
    }