Skip to content

Commit

Permalink
Add serilog example
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolayPianikov committed Dec 15, 2024
1 parent 81506c0 commit 44e05cc
Show file tree
Hide file tree
Showing 5 changed files with 289 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ dotnet run
- [Exposed roots via root arg](readme/exposed-roots-via-root-arg.md)
- [Exposed generic roots](readme/exposed-generic-roots.md)
- [Exposed generic roots with args](readme/exposed-generic-roots-with-args.md)
- [Serilog](readme/serilog.md)
### Applications
- Console
- [Schrödinger's cat](readme/Console.md)
Expand Down
12 changes: 9 additions & 3 deletions build/ReadmeTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ private static async Task AddContentAsync(string sourceFile, TextWriter readmeWr
foreach (var file in files)
{
var relativePath = Path.GetRelativePath(Environment.CurrentDirectory, file);
Part? part = default;
Part? part = null;
var vars = new Dictionary<string, string>
{
[VisibleKey] = "False",
Expand All @@ -151,7 +151,7 @@ private static async Task AddContentAsync(string sourceFile, TextWriter readmeWr

if (str.StartsWith("*/"))
{
part = default;
part = null;
continue;
}

Expand All @@ -171,7 +171,7 @@ private static async Task AddContentAsync(string sourceFile, TextWriter readmeWr
body.AddRange(localBody.Select(i => i.Length > offset ? i[offset..].TrimEnd() : i));
offset = int.MaxValue;
localBody.Clear();
part = default;
part = null;
continue;
}

Expand Down Expand Up @@ -212,6 +212,12 @@ private static async Task AddContentAsync(string sourceFile, TextWriter readmeWr
}
}

if (line.TrimStart().StartsWith("//# "))
{
localBody.Add(line.Replace("//# ", ""));
continue;
}

localBody.Add(line);
}
}
Expand Down
174 changes: 174 additions & 0 deletions readme/serilog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
#### Serilog

[![CSharp](https://img.shields.io/badge/C%23-code-blue.svg)](../tests/Pure.DI.UsageTests/Advanced/SerilogScenario.cs)


```c#
interface IDependency;

class Dependency : IDependency
{
public Dependency(ILogger<Dependency> log)
{
log.Information("created");
}
}

interface IService
{
IDependency Dependency { get; }
}

class Service : IService
{
public Service(
ILogger<Service> log,
IDependency dependency)
{
Dependency = dependency;
log.Information("created");
}

public IDependency Dependency { get; }
}

interface ILogger<T>: Serilog.ILogger;

class Logger<T>(Serilog.ILogger logger) : ILogger<T>
{
private readonly Serilog.ILogger _logger =
logger.ForContext(typeof(T));

public void Write(LogEvent logEvent) =>
_logger.Write(logEvent);
}

partial class Composition
{
private void Setup() =>
DI.Setup(nameof(Composition))
.Hint(Hint.Resolve, "Off")


Serilog.ILogger serilogLogger = CreateLogger();
var composition = new Composition(logger: serilogLogger);
var service = composition.Root;
```

The following partial class will be generated:

```c#
partial class Composition
{
private readonly Composition _root;
private readonly Lock _lock;

private Logger<Service>? _singletonLogger47;
private Logger<Dependency>? _singletonLogger48;

private readonly Serilog.ILogger _argLogger;

[OrdinalAttribute(10)]
public Composition(Serilog.ILogger logger)
{
_argLogger = logger ?? throw new ArgumentNullException(nameof(logger));
_root = this;
_lock = new Lock();
}

internal Composition(Composition parentScope)
{
_root = (parentScope ?? throw new ArgumentNullException(nameof(parentScope)))._root;
_argLogger = _root._argLogger;
_lock = _root._lock;
}

public IService Root
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_root._singletonLogger48 is null)
{
using (_lock.EnterScope())
{
if (_root._singletonLogger48 is null)
{
_root._singletonLogger48 = new Logger<Dependency>(_argLogger);
}
}
}

if (_root._singletonLogger47 is null)
{
using (_lock.EnterScope())
{
if (_root._singletonLogger47 is null)
{
_root._singletonLogger47 = new Logger<Service>(_argLogger);
}
}
}

return new Service(_root._singletonLogger47!, new Dependency(_root._singletonLogger48!));
}
}
}
```

Class diagram:

```mermaid
---
config:
class:
hideEmptyMembersBox: true
---
classDiagram
Service --|> IService
LoggerᐸServiceᐳ --|> ILoggerᐸServiceᐳ
Dependency --|> IDependency
LoggerᐸDependencyᐳ --|> ILoggerᐸDependencyᐳ
Composition ..> Service : IService Root
Service o-- "Singleton" LoggerᐸServiceᐳ : ILoggerᐸServiceᐳ
Service *-- Dependency : IDependency
LoggerᐸServiceᐳ o-- ILogger : Argument "logger"
Dependency o-- "Singleton" LoggerᐸDependencyᐳ : ILoggerᐸDependencyᐳ
LoggerᐸDependencyᐳ o-- ILogger : Argument "logger"
namespace Pure.DI.UsageTests.Advanced.SerilogScenario {
class Composition {
<<partial>>
+IService Root
}
class Dependency {
+Dependency(ILoggerᐸDependencyᐳ log)
}
class IDependency {
<<interface>>
}
class ILoggerᐸDependencyᐳ {
<<interface>>
}
class ILoggerᐸServiceᐳ {
<<interface>>
}
class IService {
<<interface>>
}
class LoggerᐸDependencyᐳ {
+Logger(ILogger logger)
}
class LoggerᐸServiceᐳ {
+Logger(ILogger logger)
}
class Service {
+Service(ILoggerᐸServiceᐳ log, IDependency dependency)
}
}
namespace Serilog {
class ILogger {
<<interface>>
}
}
```

104 changes: 104 additions & 0 deletions tests/Pure.DI.UsageTests/Advanced/SerilogScenario.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
$v=true
$p=301
$d=Serilog
*/

// ReSharper disable ClassNeverInstantiated.Local
// ReSharper disable CheckNamespace
// ReSharper disable UnusedType.Global
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedVariable

// ReSharper disable UnusedTypeParameter
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedMemberInSuper.Global
#pragma warning disable CS9113 // Parameter is unread.
namespace Pure.DI.UsageTests.Advanced.SerilogScenario;

using Serilog.Core;
using Serilog.Events;
using Xunit;

// {
interface IDependency;

class Dependency : IDependency
{
public Dependency(ILogger<Dependency> log)
{
log.Information("created");
}
}

interface IService
{
IDependency Dependency { get; }
}

class Service : IService
{
public Service(
ILogger<Service> log,
IDependency dependency)
{
Dependency = dependency;
log.Information("created");
}

public IDependency Dependency { get; }
}

interface ILogger<T>: Serilog.ILogger;

class Logger<T>(Serilog.ILogger logger) : ILogger<T>
{
private readonly Serilog.ILogger _logger =
logger.ForContext(typeof(T));

public void Write(LogEvent logEvent) =>
_logger.Write(logEvent);
}

partial class Composition
{
private void Setup() =>
DI.Setup(nameof(Composition))
// {
.Hint(Hint.Resolve, "Off")
// }
.Arg<Serilog.ILogger>("logger")
.Bind().As(Lifetime.Singleton).To<Logger<TT>>()

.Bind().To<Dependency>()
.Bind().To<Service>()
.Root<IService>(nameof(Root));
}
// }

class EventSink(ICollection<LogEvent> events)
: ILogEventSink
{
public void Emit(LogEvent logEvent) =>
events.Add(logEvent);
}

public class Scenario
{
[Fact]
public void Run()
{
var events = new List<LogEvent>();
var serilogLogger = new Serilog.LoggerConfiguration()
.WriteTo.Sink(new EventSink(events))
.CreateLogger();
// {
//# Serilog.ILogger serilogLogger = CreateLogger();
var composition = new Composition(logger: serilogLogger);
var service = composition.Root;
// }
events.Count.ShouldBe(2);
composition.SaveClassDiagram();
}
}
1 change: 1 addition & 0 deletions tests/Pure.DI.UsageTests/Pure.DI.UsageTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<Compile Include="..\..\src\Pure.DI.MS\any\Pure.DI\MS\*.cs" Link=""/>
<PackageReference Include="Castle.Core" Version="5.1.1"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Shouldly" Version="4.2.1"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="xunit" Version="2.9.2" />
Expand Down

0 comments on commit 44e05cc

Please sign in to comment.