using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using static System.Guid;
namespace myWatchList
{
internal class Program
{
static void Main(string[] args)
{
//setup our DI
var serviceProvider = new ServiceCollection()
.AddLogging(c => c.AddConsole(opt => opt.LogToStandardErrorThreshold = LogLevel.Debug))
.AddSingleton<IFooService, FooService>()
.AddSingleton<IBarService, BarService>()
.BuildServiceProvider();
//configure console logging
serviceProvider
.GetService<ILoggerFactory>();
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogInformation("Starting application");
//do the actual work here
var bar = serviceProvider.GetService<IBarService>();
bar.DoSomeRealWork();
logger.LogDebug("All done!");
}
}
public interface IFooService
{
void DoThing(int number);
}
public interface IBarService
{
void DoSomeRealWork();
}
public class BarService : IBarService
{
private readonly IFooService _fooService;
public BarService(IFooService fooService)
{
_fooService = fooService;
}
public void DoSomeRealWork()
{
for (int i = 0; i < 10; i++)
{
_fooService.DoThing(i);
}
}
}
public class FooService : IFooService
{
private readonly ILogger<FooService> _logger;
public FooService(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<FooService>();
}
public void DoThing(int number)
{
_logger.LogInformation($"Doing the thing {number}");
}
}
}
Thursday, 19 May 2022
Using dependency Injection in .Net Core 6
Subscribe to:
Post Comments (Atom)
Search This Blog
Creating your first "Alexa" Skill
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
About Me
Menu
-
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
-
Adding Azure AD B2C to React Native App Register your app in Azure active directory 1. Go to azure ad b2c, app registratio...
-
# Project file 1. .net Core project file no longer contains file or folder reference - all files and folder present within the root fol...
No comments:
Post a Comment