简体   繁体   English

ASP.NET Core:带条件的DI服务

[英]ASP.NET Core: DI Service with conditions

I want to register my service class ADManager in Startup. 我想在启动中注册我的服务类ADManager。 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. 但是该类在构造函数中具有字符串参数,实例化取决于用户是否与webb应用程序位于同一域。

// 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: 但是,如果_isSameDomain等于false,则必须像这样创建它:

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

You need to use the factory overload of AddScoped . 您需要使用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. 每次实例化该服务时,作为工厂传递的lambda都会在实例化的整个生命周期内运行,并且大致是每个请求。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM