.Net Core dependency injection in console app

In the previous post, I explain to you Dependency injection and why it is essential to every software project. In this article, I will show you how to configure DI in a .net core console application. I choose console application because if you create an web application project, then Dependency injection is configured. I will tell you from scratch how to configure the console application. By the end of the tutorial you will be able to understand how to implement dependency injection in console application in C#.

This tutorial is about how to add dependency injection in .NET core console application.

Create a Console Application in Visual Studio and add two interface IFoo and IBar.

public interface IFoo
{
	void GetData();
}

public interface IBar
{
	string GetData();
} 

Now create two classes FooService and BarService and implement the interfaces as shown below

BarService.cs

public class BarService : IBar
{
	public BarService()
	{

	}
	public string GetData()
	{
		return "Data From Bar Service";

	}
}

FooService.cs

public class FooService : IFoo
{
	private readonly ILogger _logger;
	private readonly IBar _bar;

	public FooService(ILogger<FooService> logger, IBar bar)
	{
		_logger = logger;
		_bar = bar;

	}

	public void GetData()
	{
		_logger.LogInformation(_bar.GetData());

	}

}

You can see in the BarService has dependency with the BarService and Logger and we are not using new keyword anywhere.

Now it’s time to configure Dependency Container before that we need to install Microsoft.Extensions.DependencyInjection from NuGet. Open a Command prompt and run the following command

dotnet add package Microsoft.Extensions.DependencyInjection

Once the installation is done. Create a new class Startup.cs and add the following code.

public class Startup
{


	public static ServiceProvider Configure()
	{
		var provider = new ServiceCollection()
					.AddSingleton<IFoo, FooService>()
					.AddSingleton<IBar, BarService>()
					.AddLogging(fs => fs.AddConsole())
					.BuildServiceProvider(validateScopes: true);
		return provider;
	}

}

The above code is self-explanatory. I am adding the dependency to the container so that it provided concrete completion when someone requested it.

Now open Program.cs and add the following code

void Main()
{
	var container = Startup.Configure();
	var fooService = container.GetService<IFoo>();
	fooService.GetData();

}

If you run the application, you will see the following output.

info: FooService[0]
      Data From Bar Service

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru