Reputation: 3707
As you can tell from this question I’m still a newbie with .Net Core and understanding about Dependency Injection.
I’m in the process of writing a .Net Core Console app and I was finally able to get to a point where I’m doing a little bit of DI for logging and configuration settings. What I’m not understanding is using DI when calling another class from within a class.
I created a class called AppHost which has a function called Run() in it. In my Program.cs I’ve setup DI and then will call the AppHost.Run() to execute my main code.
Inside of my AppHost I need to call some database functions in another file I’ve called Data/DataManager. My understanding was that I would setup the class in the DI container and would be able to get my logging and configuration from there. As far as I know, I’ve done that in my “host” declaration. However, when I call my DataManager.GetActiveEmployees() it’s wanting me to create an object since my DataManager is not set a static. When I create a DataManager object it is wanting me to pass in my logger and configuration since that is what is in the constructor of the class. I can do that but is sure seems like that is not the correct way to do it. I thought with DI I would be able to get the logger and configuration out of DI and not need to pass it into the object? Am I supposed to create the DataManager object and pass the logger and configuration from my AppHost into it?
Program.cs
var host = Host.CreateDefaultBuilder().ConfigureServices((context, services) =>
{
services.AddTransient<IAppHost, AppHost>();
services.AddTransient<IFileManager, FileManager>();
services.AddTransient<IDataManager, DataManager>();
services.AddLogging(builder =>
{
builder.AddNLog("nlog.config");
});
}).Build();
var svc = ActivatorUtilities.CreateInstance<AppHost>(host.Services);
svc.Run();
AppHost.cs
private void CheckEmailAddresses()
{
DataManager oDataManager = new DataManager();
var listEmployees = new List<Employee>();
listEmployees = oDataManager.GetActiveEmployees();
}
DataManager.cs
public class DataManager : IDataManager
{
private readonly ILogger<DataManager> _log;
private readonly IConfiguration _configuration;
public DataManager(ILogger<DataManager> log, IConfiguration config)
{
_log = log;
_configuration = config;
}
}
Upvotes: 0
Views: 2380
Reputation: 2567
You've already registered your IDataManager in DI dependency. So, instead of doing new
which killing the purpose of DI anyway you need to change your CheckEmailAddresses
like this.
private void YouClassName()
{
private readonly IDataManager _dataManager;
public YouClassName(IDataManager dataManager)
{
_dataManager = dataManger.
}
private void CheckEmailAddresses()
{
var listEmployees = new List<Employee>();
listEmployees = _dataManager.GetActiveEmployees();
}
}
Now we are inject IDataManager
into your class and your other dependencies like Logger
will be build automatically.
Upvotes: 2