0

In my CLI Main I need a object of my MonDbBusinessComponent class. I wrote the code below, but my object is still null. What's wrong? How to do it right?

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
  • It's hard to tell, because your example doesn't show what GetServiceProvider() is doing. It's likely null because IMonDbBusinessComponent isn't in the service collection. Commented Sep 12, 2019 at 20:07
  • Is your program a console app? You may not need dependency injection with a service collection at all. Can you simply do new MonDbBusinessComponent(new MonDbRepository? Commented Sep 12, 2019 at 20:09

2 Answers 2

1

you never registered your IMonDbBusinessComponent.

collection.AddScoped<IMonDbBusinessComponent, MonDbBusinessComponent>();
Sign up to request clarification or add additional context in comments.

1 Comment

Thats right. I register a other class.(Repository instead of BusinessComponent.) But now after adding BusinessComponent my object is still null.
0

I'm sorry, it was not possible to see in my published coded. The BusinessComponent uses Repository and first I needed to register the Repository with it's arguments and then register the BusinessComponent. Also at the BusinessComonent I needed to use the Interface instead of the 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>();

Thanks for all support!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.