Skip to main content
 首页 » 编程设计

c#之在 mvc 中使用依赖注入(inject)

2024年02月05日11Leo_wl

在我们的一个应用程序中,我已经在使用 AppTenant 类的依赖注入(inject),如下所示

public void ConfigureServices(IServiceCollection services) 
{ 
 
services.AddMultitenancy<AppTenant, CachingAppTenantResolver>(); 
services.Configure<MultitenancyOptions>(Configuration.GetSection("Multitenancy")); 
} 
 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
 app.UseMultitenancy<AppTenant>(); 
} 

在 Controller 中,我可以按如下方式轻松访问它

public AccountController(AppTenant tenant) 
    { 
        this.tenant = tenant; 
    } 

现在,我想在同一解决方案的其他项目类中访问相同的 AppTenant 或 HttpContext。 所以,我试过这样

public SqlStringLocalizerFactory( 
       AppTenant tenant) 
    { 
     _tenant = tenant; 
 
    } 

但它即将变为 null,所以我需要做的是在其他项目类中获取 AppTenant 或 HttpContext 吗?

对于 SqlStringLocalizerFactory 类,服务是在 ConfigureServices 方法中编写的,如下所示

public static class SqlLocalizationServiceCollectionExtensions 
{ 
 
    public static IServiceCollection AddSqlLocalization(this IServiceCollection services) 
    { 
        if (services == null) 
        { 
            throw new ArgumentNullException(nameof(services)); 
        } 
 
        return AddSqlLocalization(services, setupAction: null); 
    } 
 
   public static IServiceCollection AddSqlLocalization( 
        this IServiceCollection services, 
       Action<SqlLocalizationOptions> setupAction) 
    { 
 
            if (services == null) 
        { 
            throw new ArgumentNullException(nameof(services)); 
        } 
 
        services.TryAdd(new ServiceDescriptor( 
            typeof(IStringExtendedLocalizerFactory), 
            typeof(SqlStringLocalizerFactory), 
            ServiceLifetime.Singleton)); 
        services.TryAdd(new ServiceDescriptor( 
            typeof(IStringLocalizerFactory), 
            typeof(SqlStringLocalizerFactory), 
            ServiceLifetime.Singleton)); 
        services.TryAdd(new ServiceDescriptor( 
            typeof(IStringLocalizer), 
            typeof(SqlStringLocalizer), 
            ServiceLifetime.Singleton)); 
 
        if (setupAction != null) 
        { 
            services.Configure(setupAction); 
        } 
        return services; 
    } 
} 

我什至尝试过使用 IHttpContextAccessor,但仍然没有取得任何成功。

在此感谢任何帮助!

请您参考如下方法:

Edit-2

新解决方案:

public SqlStringLocalizerFactory(IHttpContextAccessor _accessor) 
{ 
   _accessor= accessor; 
} 
public void SomeMethod() 
{ 
    var tenant = _accessor.HttpContext.RequestServices 
            .GetRequiredService<AppTenant>(); 
} 

编辑:IServiceProvider 方式无法正常工作。查看@Sock的解决方案

首先,我假设问题的发生是由于@qujck 指出的俘虏依赖。为了避免俘虏依赖:

如果 SqlStringLocalizerFactory 的生命周期必须是单例的(某些情况下必须是),在这个 案例使用IServiceProvider:

public SqlStringLocalizerFactory(IServiceProvider serviceProvider) 
{ 
   _serviceProvider = serviceProvider; 
} 
public void SomeMethod() 
{ 
    var tenant =  _serviceProvider.GetService<AppTenant>(); 
} 

否则使用 AddScoped 对您的情况来说似乎是合理的。