how to injection dependency in net core by name code example
Example 1: add dependency injection .net core console app
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
public class Program
{
public static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddLogging()
.AddSingleton<IFooService, FooService>()
.AddSingleton<IBarService, BarService>()
.BuildServiceProvider();
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogDebug("Starting application");
var bar = serviceProvider.GetService<IBarService>();
bar.DoSomeRealWork();
logger.LogDebug("All done!");
}
}
Example 2: add dependency injection .net core console app
{
"dependencies": {
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.DependencyInjection": "1.0.0"
}
}