使用DI引导包含多个模块类型的ASP.NET Core 2.1应用程序

问题描述 投票:0回答:1

开始为多租户ASP.NET Core 2.1应用程序构建基础结构,该应用程序将由许多模块组成。

我们的想法是,将未来添加的任何模块插入系统,在应用程序启动时注册自己所需的依赖项,并在需要时使用已注册的依赖项(其他模块注册的依赖项)。

让我们首先看看我想象的样本代码 - 从我的头顶。假设我们有一种模块管理器,我们就是这样命名的 - ModuleManager

public class ModuleManager
{
    // Let's store all of our module types here
    private List<Type> moduleTypes;

    void RegisterModules(Type webHostModuleType, IServiceCollection services)
    {
        // Find all module dependencies recursively 
        // (i.e. all modules that are specified in some, let's say 'DependsOn' attribute
        // which decorates webHostModuleType)
        moduleTypes = FindDependencies();

        // Now we need to register all dependencies
        foreach (Type moduleType in moduleTypes)
        {
            services.AddSingleton(moduleType);
        }

        // ... and we shouldn't forget to register the webHostModuleType too
        services.AddSingleton(webHostModuleType);
    }
}

我们暂时停在那里,首先定义模块类型。我认为应该假设每个模块类型可以根据需要具有不同的属性和字段,但我们必须使它们都来自基本模块类型。我们称之为BaseModule,这就是我想象的那样:

public abstract class BaseModule
{
    // I've currently got no idea on how this method should be defined
    // Because it's supposed to register the concrete module's dependencies
    // after the module has been instantiated... is that even possible?
    // Should it be some kind of a factory method rather than void 
    // and serve as a lazy initializer? Is that also even possible?
    // Something that should make use of IOptions<>?
    public virtual void Init()
    {
    }

    // Maybe some post-init code will be needed too
    public virtual void PostInit()
    {
    }
}

然后我们将有一些具体的模块类型定义如下:

public class CoreModule : BaseModule
{
    // some dependencies that need to be injected...
    private readonly IHostingEnvironment hostingEnvironment;

    private readonly IDontKnowSomeOtherDependency someOtherDependency;

    public CoreModule(IHostingEnvironment hostingEnvironment, IDontKnowSomeOtherDependency someOtherDependency)
    {
        this.hostingEnvironment = hostingEnvironment;
        this.someOtherDependency = someOtherDependency;
    }

    public override void Init()
    {
        // Somehow register additional services defined by this module,
        // after it's been instantiated
    }
}

让我们说,为了完整起见,我们的webHostModuleType定义如下:

[DependsOn(typeof(CoreModule))]
public class WebHostModule : BaseModule
{
    private readonly ISomeDependencyRegisteredInCoreModule someDependency;

    public WebHostModule(ISomeDependencyRegisteredInCoreModule someDependency)
    {
        this.someDependency = someDependency;
    }

    public override void Init()
    {
        // Register some other service based on something from 'someDependency' field
    }
}

最后,让我们回到模块管理器。现在它应该有另一个方法,在RegisterModules之后执行,它应该以正确的顺序实例化每个模块,然后以正确的顺序调用Init()PostInit(),从CoreModule开始,以WebHostModule结束。类似于此的东西:

public void(?) LoadModules()
{
    // Sort our modules first so dependencies come in first and webHostModuleType the last
    SortEm(moduleTypes);

    // Now we need to instantiate them. 
    // Can't do it manually as all of them might have different constructors
    // So need to do it using our service collection 
    IServiceProvider serviceProvider = serviceCollection.BuildServicePRovider();

    foreach (Type moduleType in moduleTypes)
    {
        BaseModule moduleInstance = serviceProvider.GetRequiredService(moduleType) as BaseModule;

        // This is where we can register everything needed by the module instance. 
        // But can we?
        moduleInstance.Init();
        moduleInstance.PostInit();
    }

    // Maybe return the IServiceProvider instance we've built 
    // so we can return in to the `ConfigureServices` and return to ASP.NET Core from there?
}

如您所见,这种方法引发了许多问题。我是否正朝着正确的方向前进?有没有办法正确注册模块的Init()PostInit()方法的服务?

如果我调用BuildServiceProvider()然后实例化单例实例,我将不得不将IServiceProvider实例返回到ConfigureServices(),以便ASP.NET Core可以使用它。如果我不这样做,它将构建一个新的,然后所有这些单例将再次实例化。

但是,如果我调用ConfigureServices()然后我将无法添加新服务,我必须在模块实例化之后执行此操作。如果有可能的话,方法是什么?任何意见,想法?

哇这样的文字墙,感谢阅读!

c# asp.net-core dependency-injection
1个回答
0
投票

好吧,还有一个意见,但我们使用与Net Core团队相同的标准广告,创建扩展方法,所以我们只需要添加他们需要的服务:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddVtaeCommonServices();
        services.AddMyServiceMX(Configuration);
        services.AddOtherService(Configuration);

        return VtaeConfig.ConfigVtae(services);
    }
}

使用此扩展方法,例如:

public static class CommonServicesExtension
{

    public static IServiceCollection AddVtaeCommonServices(this IServiceCollection services)
    {
        services.AddNodaDateTime();
        services.AddMemoryCache();
        services.AddScoped<AuthorizedIpFilter>();
        services.AddScoped<HttpContextManager>();
        services.AddTransient<ProspectService>();
        services.AddTransient<TokenService>();
        services.AddTransient<TokenGenerator>();
        services.AddTransient<ProspectsRepository>();
        services.AddSingleton<UniqueIDGenerator>();
        services.AddSingleton<SchedulerService>();
        services.AddSingleton<ChecksumService>();
        return services;
    }
}

通过这种方式,我们可以将我们的函数提取到nuget包中,然后通过在启动时添加AddXXXService()来重新利用它们

© www.soinside.com 2019 - 2024. All rights reserved.