CLI Main中的依赖注入,对象为null

时间:2019-09-12 19:45:53

标签: c# asp.net-core dependency-injection .net-core command-line-interface

在我的CLI Main中,我需要一个MonDbBusinessComponent类的对象。 我写了下面的代码,但我的对象仍然为空。 怎么了?怎么做对呢?

public static IMonDbBusinessComponent monDbBusinessComponent { get; set; }
static void Main(string[] args)
{
    var collection = new ServiceCollection();
    collection.AddScoped<IMonDbRepository, MonDbRepository>();
    ServiceProvider appServiceProvider = GetServiceProvider();
    monDbBusinessComponent = appServiceProvider.GetService<IMonDbBusinessComponent>();

2 个答案:

答案 0 :(得分:1)

您从未注册过IMonDbBusinessComponent。

collection.AddScoped<IMonDbBusinessComponent, MonDbBusinessComponent>();

答案 1 :(得分:0)

很抱歉,在我发布的代码中看不到。 BusinessComponent使用存储库,首先我需要使用其参数注册存储库,然后注册BusinessComponent。 同样在BusinessComonent,我需要使用Interface而不是class。

public MonDbBusinessComponent(IMonDbRepository monDbRepository){...}

collection.AddScoped<IMonDbRepository>(ServiceProvider =>
{
    string createMetaDataRecordFunctionName = Configurations.Get(LocalConfiguration, "CreateMetaDataRecordFunctionName");
    string conDbDataRecordFunctionName = Configurations.Get(LocalConfiguration, "ConDbDataRecordFunctionName");
    return new MonDbRepository(metaDataConnection, createMetaDataRecordFunctionName, conDbDataRecordFunctionName);
});
collection.AddScoped<IMonDbBusinessComponent, MonDbBusinessComponent>();

感谢所有支持!