Code cleanup and enforce csharpier

This commit is contained in:
Holger Börchers 2022-11-13 21:03:26 +01:00
parent 32cc67b25a
commit 8884d55380
19 changed files with 281 additions and 312 deletions

6
.csharpierrc Normal file

@ -0,0 +1,6 @@
{
"printWidth": 200,
"useTabs": false,
"tabWidth": 4,
"preprocessorSymbolSets": ["", "DEBUG", "DEBUG,CODE_STYLE"]
}

3
.filenesting.json Normal file

@ -0,0 +1,3 @@
{
"help":"https://go.microsoft.com/fwlink/?linkid=866610"
}

@ -1,98 +1,90 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace SmallInjector;
namespace SmallInjector
/// <summary>
/// A small dependency injector to demonstrate the pattern.
/// </summary>
public class Container : IContainer
{
/// <summary>
/// A small dependency injector to demonstrate the pattern.
/// </summary>
public class Container : IContainer
private readonly Dictionary<Type, List<RegisteredType>> _container = new();
/// <inheritdoc/>
public void RegisterType<TService, TInterface>(bool isSingleton, TService instance = default) where TService : TInterface
{
private readonly Dictionary<Type, List<RegisteredType>> _container = new Dictionary<Type, List<RegisteredType>>();
/// <inheritdoc/>
public void RegisterType<TService, TInterface>(bool isSingleton, TService instance = default)
where TService : TInterface
if (!IsRegistered<TInterface>())
{
if (!IsRegistered<TInterface>())
{
_container[typeof(TInterface)] = new List<RegisteredType>
{new RegisteredType(typeof(TService), isSingleton, null)};
}
else
{
_container[typeof(TInterface)].Add(new RegisteredType(typeof(TService), isSingleton, null));
}
_container[typeof(TInterface)] = new List<RegisteredType> { new RegisteredType(typeof(TService), isSingleton, null) };
}
/// <inheritdoc/>
public void RegisterType<TService>(bool isSingleton, TService instance = default) =>
RegisterType<TService, TService>(isSingleton, instance);
/// <inheritdoc/>
public TService Resolve<TService>() => (TService) Resolve(typeof(TService));
/// <inheritdoc />
public bool IsRegistered<TService>() => IsRegistered(typeof(TService));
/// <inheritdoc />
public bool IsRegistered(Type serviceType) => _container.ContainsKey(serviceType);
/// <inheritdoc />
public IEnumerable<object> ResolveAny(Type serviceType)
else
{
if (!_container.TryGetValue(serviceType, out var registeredTypes))
throw new Exception($"Dependency {serviceType.FullName} is not registered");
foreach (var registeredType in registeredTypes)
{
if (registeredType.IsSingleton && registeredType.Instance != null)
{
yield return registeredType.Instance;
continue;
}
var constructor = registeredType.ServiceType.GetConstructors()[0];
var parameters = constructor.GetParameters();
var constructorParameters = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var parameterType = parameters[i].ParameterType;
if (typeof(Array).IsAssignableFrom(parameterType))
{
constructorParameters[i] = ResolveAny(parameterType.GetElementType()).ToArray();
}
else
{
constructorParameters[i] = Resolve(parameters[i].ParameterType);
}
}
var instance = constructor.Invoke(constructorParameters);
yield return registeredType.IsSingleton ? (registeredType.Instance = instance) : instance;
}
}
/// <inheritdoc />
public IEnumerable<object> ResolveAny<TService>() => ResolveAny(typeof(TService));
/// <inheritdoc/>
public object Resolve(Type serviceType) => ResolveAny(serviceType).First();
private class RegisteredType
{
public bool IsSingleton { get; }
public Type ServiceType { get; }
public object Instance { get; set; }
public RegisteredType(Type serviceType, bool isSingleton, object instance)
{
ServiceType = serviceType;
IsSingleton = isSingleton;
Instance = instance;
}
public override string ToString() => ServiceType.ToString();
_container[typeof(TInterface)].Add(new RegisteredType(typeof(TService), isSingleton, null));
}
}
}
/// <inheritdoc/>
public void RegisterType<TService>(bool isSingleton, TService instance = default) => RegisterType<TService, TService>(isSingleton, instance);
/// <inheritdoc/>
public TService Resolve<TService>() => (TService)Resolve(typeof(TService));
/// <inheritdoc />
public bool IsRegistered<TService>() => IsRegistered(typeof(TService));
/// <inheritdoc />
public bool IsRegistered(Type serviceType) => _container.ContainsKey(serviceType);
/// <inheritdoc />
public IEnumerable<object> ResolveAny(Type serviceType)
{
if (!_container.TryGetValue(serviceType, out var registeredTypes))
throw new Exception($"Dependency {serviceType.FullName} is not registered");
foreach (var registeredType in registeredTypes)
{
if (registeredType.IsSingleton && registeredType.Instance != null)
{
yield return registeredType.Instance;
continue;
}
var constructor = registeredType.ServiceType.GetConstructors()[0];
var parameters = constructor.GetParameters();
var constructorParameters = new object[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
var parameterType = parameters[i].ParameterType;
if (typeof(Array).IsAssignableFrom(parameterType))
{
constructorParameters[i] = ResolveAny(parameterType.GetElementType()).ToArray();
}
else
{
constructorParameters[i] = Resolve(parameters[i].ParameterType);
}
}
var instance = constructor.Invoke(constructorParameters);
yield return registeredType.IsSingleton ? (registeredType.Instance = instance) : instance;
}
}
/// <inheritdoc />
public IEnumerable<object> ResolveAny<TService>() => ResolveAny(typeof(TService));
/// <inheritdoc/>
public object Resolve(Type serviceType) => ResolveAny(serviceType).First();
private class RegisteredType
{
public bool IsSingleton { get; }
public Type ServiceType { get; }
public object Instance { get; set; }
public RegisteredType(Type serviceType, bool isSingleton, object instance)
{
ServiceType = serviceType;
IsSingleton = isSingleton;
Instance = instance;
}
public override string ToString() => ServiceType.ToString();
}
}

@ -1,55 +1,51 @@
using System;
using System.Collections.Generic;
namespace SmallInjector;
namespace SmallInjector
/// <summary>
/// DI Container
/// </summary>
public interface IContainer
{
/// <summary>
/// DI Container
/// Register types in the resolve container.
/// </summary>
public interface IContainer
{
/// <summary>
/// Register types in the resolve container.
/// </summary>
/// <typeparam name="TService">Type of the service.</typeparam>
/// <typeparam name="TInterface">Type of the interface of the service.</typeparam>
/// <param name="isSingleton">True if the service should be singleton. False otherwise.</param>
/// <param name="instance">instance of the service</param>
void RegisterType<TService, TInterface>(bool isSingleton, TService instance = default) where TService : TInterface;
/// <summary>
/// Register types in the resolve container.
/// </summary>
void RegisterType<TService>(bool isSingleton, TService instance = default);
/// <typeparam name="TService">Type of the service.</typeparam>
/// <typeparam name="TInterface">Type of the interface of the service.</typeparam>
/// <param name="isSingleton">True if the service should be singleton. False otherwise.</param>
/// <param name="instance">instance of the service</param>
void RegisterType<TService, TInterface>(bool isSingleton, TService instance = default) where TService : TInterface;
/// <summary>
/// Resolve service of specified type.
/// </summary>
object Resolve(Type serviceType);
/// <summary>
/// Register types in the resolve container.
/// </summary>
void RegisterType<TService>(bool isSingleton, TService instance = default);
/// <summary>
/// Resolve service of specified type.
/// </summary>
TService Resolve<TService>();
/// <summary>
/// Resolve service of specified type.
/// </summary>
object Resolve(Type serviceType);
/// <summary>
/// Returns true, if the service is registered. False otherwise.
/// </summary>
bool IsRegistered<TService>();
/// <summary>
/// Resolve service of specified type.
/// </summary>
TService Resolve<TService>();
/// <summary>
/// Returns true, if the service is registered. False otherwise.
/// </summary>
bool IsRegistered(Type serviceType);
/// <summary>
/// Returns true, if the service is registered. False otherwise.
/// </summary>
bool IsRegistered<TService>();
/// <summary>
/// Resolve any implementation
/// </summary>
IEnumerable<object> ResolveAny(Type serviceType);
/// <summary>
/// Resolve any implementation
/// </summary>
IEnumerable<object> ResolveAny<TService>();
}
}
/// <summary>
/// Returns true, if the service is registered. False otherwise.
/// </summary>
bool IsRegistered(Type serviceType);
/// <summary>
/// Resolve any implementation
/// </summary>
IEnumerable<object> ResolveAny(Type serviceType);
/// <summary>
/// Resolve any implementation
/// </summary>
IEnumerable<object> ResolveAny<TService>();
}

@ -1,8 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

@ -1,12 +1,17 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29123.88
# Visual Studio Version 17
VisualStudioVersion = 17.4.33103.184
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SmallInjectorDemo", "SmallInjectorDemo\SmallInjectorDemo.csproj", "{620CC001-7DF9-4233-AFC2-187FD9144835}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SmallInjector", "SmallInjector\SmallInjector.csproj", "{8D52C856-A71D-4C50-832B-8679CDD030B4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{97F8F459-C4B4-4C40-A4CA-2443A9C245D9}"
ProjectSection(SolutionItems) = preProject
.csharpierrc = .csharpierrc
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU

@ -1,47 +1,44 @@
using System;
using System.Buffers.Text;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo
namespace SmallInjectorDemo;
/// <summary>
/// Static helper class for generating random numbers.
/// </summary>
public static class Helper
{
/// <summary>
/// Static helper class for generating random numbers.
/// Encode Base64 string
/// </summary>
public static class Helper
public static string EncodeBase64String(this Guid guid)
{
/// <summary>
/// Encode Base64 string
/// </summary>
public static string EncodeBase64String(this Guid guid)
{
Span<byte> guidBytes = stackalloc byte[16];
Span<byte> encodedBytes = stackalloc byte[24];
Span<byte> guidBytes = stackalloc byte[16];
Span<byte> encodedBytes = stackalloc byte[24];
MemoryMarshal.TryWrite(guidBytes, ref guid); // write bytes from the Guid
Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _);
MemoryMarshal.TryWrite(guidBytes, ref guid); // write bytes from the Guid
Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _);
// skip the last two bytes as these will be '==' padding
var final = Encoding.UTF8.GetString(encodedBytes.Slice(0, 22));
// skip the last two bytes as these will be '==' padding
var final = Encoding.UTF8.GetString(encodedBytes.Slice(0, 22));
return final;
}
/// <summary>
/// Write method string.
/// </summary>
/// <param name="clock">The current clock</param>
/// <param name="id">id of the object</param>
/// <param name="memberName">member name</param>
/// <param name="filepath">file path</param>
/// <returns></returns>
public static string WriteMethodString(IClock clock, string id, [CallerMemberName] string memberName = null, [CallerFilePath] string filepath = null)
{
var classname = Path.GetFileNameWithoutExtension(filepath);
return $"[{clock.CurrentDateTime}] {classname}.{memberName?.TrimStart('.')}".PadRight(30) + $"Id: {id}";
}
return final;
}
}
/// <summary>
/// Write method string.
/// </summary>
/// <param name="clock">The current clock</param>
/// <param name="id">id of the object</param>
/// <param name="memberName">member name</param>
/// <param name="filepath">file path</param>
/// <returns></returns>
public static string WriteMethodString(IClock clock, string id, [CallerMemberName] string memberName = null, [CallerFilePath] string filepath = null)
{
var classname = Path.GetFileNameWithoutExtension(filepath);
return $"[{clock.CurrentDateTime}] {classname}.{memberName?.TrimStart('.')}".PadRight(30) + $"Id: {id}";
}
}

@ -1,13 +1,12 @@
namespace SmallInjectorDemo.Interfaces
namespace SmallInjectorDemo.Interfaces;
/// <summary>
/// Interface of the clock.
/// </summary>
public interface IClock
{
/// <summary>
/// Interface of the clock.
/// Current Date-Time.
/// </summary>
public interface IClock
{
/// <summary>
/// Current Date-Time.
/// </summary>
string CurrentDateTime { get; }
}
}
string CurrentDateTime { get; }
}

@ -1,9 +1,6 @@
namespace SmallInjectorDemo.Interfaces
{
/// <summary>
/// Defines the <see cref="IModule" />
/// </summary>
public interface IModule
{
}
}
namespace SmallInjectorDemo.Interfaces;
/// <summary>
/// Defines the <see cref="IModule" />
/// </summary>
public interface IModule { }

@ -1,10 +1,6 @@
namespace SmallInjectorDemo.Interfaces
{
/// <summary>
/// Interface for service one.
/// </summary>
public interface IServiceOne
{
namespace SmallInjectorDemo.Interfaces;
}
}
/// <summary>
/// Interface for service one.
/// </summary>
public interface IServiceOne { }

@ -1,10 +1,6 @@
namespace SmallInjectorDemo.Interfaces
{
/// <summary>
/// Interface for service two.
/// </summary>
public interface IServiceTwo
{
namespace SmallInjectorDemo.Interfaces;
}
}
/// <summary>
/// Interface for service two.
/// </summary>
public interface IServiceTwo { }

@ -1,11 +1,8 @@
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo.Items
{
/// <summary>
/// Defines the <see cref="ModuleA" />
/// </summary>
public class ModuleA : IModule
{
}
}
namespace SmallInjectorDemo.Items;
/// <summary>
/// Defines the <see cref="ModuleA" />
/// </summary>
public class ModuleA : IModule { }

@ -1,11 +1,8 @@
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo.Items
{
/// <summary>
/// Defines the <see cref="ModuleB" />
/// </summary>
public class ModuleB : IModule
{
}
}
namespace SmallInjectorDemo.Items;
/// <summary>
/// Defines the <see cref="ModuleB" />
/// </summary>
public class ModuleB : IModule { }

@ -1,11 +1,8 @@
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo.Items
{
/// <summary>
/// Defines the <see cref="ModuleC" />
/// </summary>
public class ModuleC : IModule
{
}
}
namespace SmallInjectorDemo.Items;
/// <summary>
/// Defines the <see cref="ModuleC" />
/// </summary>
public class ModuleC : IModule { }

@ -19,7 +19,6 @@ container.RegisterType<ModuleA, IModule>(true);
container.RegisterType<ModuleB, IModule>(true);
container.RegisterType<ModuleC, IModule>(true);
Console.WriteLine();
Console.WriteLine("Check registrations:");
Console.WriteLine(nameof(IClock).PadRight(20) + container.IsRegistered<IClock>());
@ -38,4 +37,4 @@ useful1.TestTheServices();
Console.WriteLine();
useful2.TestTheServices();
Console.WriteLine();
useful3.TestTheServices();
useful3.TestTheServices();

@ -1,45 +1,42 @@
using System;
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo
namespace SmallInjectorDemo;
/// <summary>
/// A very useful class.
/// </summary>
public class ServiceConsumer
{
private readonly IClock _clock;
private readonly IServiceOne _service1;
private readonly IServiceTwo _service2;
private readonly string _id;
/// <summary>
/// A very useful class.
/// Creates a new instance of <see cref="ServiceConsumer"/>.
/// </summary>
public class ServiceConsumer
/// <param name="clock">The current clock</param>
/// <param name="service1">injected service one.</param>
/// <param name="service2">injected service two.</param>
public ServiceConsumer(IClock clock, IServiceOne service1, IServiceTwo service2)
{
private readonly IClock _clock;
private readonly IServiceOne _service1;
private readonly IServiceTwo _service2;
private readonly string _id;
/// <summary>
/// Creates a new instance of <see cref="ServiceConsumer"/>.
/// </summary>
/// <param name="clock">The current clock</param>
/// <param name="service1">injected service one.</param>
/// <param name="service2">injected service two.</param>
public ServiceConsumer(IClock clock, IServiceOne service1, IServiceTwo service2)
{
_clock = clock;
_service1 = service1;
_service2 = service2;
_id = Guid.NewGuid().EncodeBase64String();
Console.WriteLine(Helper.WriteMethodString(clock, _id));
}
/// <summary>
/// Test the injected services.
/// </summary>
public void TestTheServices()
{
Console.WriteLine(ToString());
Console.WriteLine(_service1.ToString());
Console.WriteLine(_service2.ToString());
}
/// <inheritdoc />
public override string ToString() => Helper.WriteMethodString(_clock, _id);
_clock = clock;
_service1 = service1;
_service2 = service2;
_id = Guid.NewGuid().EncodeBase64String();
Console.WriteLine(Helper.WriteMethodString(clock, _id));
}
}
/// <summary>
/// Test the injected services.
/// </summary>
public void TestTheServices()
{
Console.WriteLine(ToString());
Console.WriteLine(_service1.ToString());
Console.WriteLine(_service2.ToString());
}
/// <inheritdoc />
public override string ToString() => Helper.WriteMethodString(_clock, _id);
}

@ -1,29 +1,26 @@
using System;
using System.Collections.Generic;
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo
namespace SmallInjectorDemo;
/// <inheritdoc />
/// <summary>
/// Implementation of <see cref="T:SmallInjectorDemo.IServiceOne" />.
/// </summary>
public class ServiceOne : IServiceOne
{
/// <inheritdoc />
private readonly IClock _clock;
private readonly string _id;
/// <summary>
/// Implementation of <see cref="T:SmallInjectorDemo.IServiceOne" />.
/// Creates a new instance of <see cref="ServiceOne"/>.
/// </summary>
public class ServiceOne : IServiceOne
public ServiceOne(IClock clock)
{
private readonly IClock _clock;
private readonly string _id;
/// <summary>
/// Creates a new instance of <see cref="ServiceOne"/>.
/// </summary>
public ServiceOne(IClock clock, IModule[] modules)
{
_clock = clock;
_id = Guid.NewGuid().EncodeBase64String();
Console.WriteLine(Helper.WriteMethodString(clock, _id));
}
/// <inheritdoc />
public override string ToString() => Helper.WriteMethodString(_clock, _id);
_clock = clock;
_id = Guid.NewGuid().EncodeBase64String();
Console.WriteLine(Helper.WriteMethodString(clock, _id));
}
}
/// <inheritdoc />
public override string ToString() => Helper.WriteMethodString(_clock, _id);
}

@ -1,4 +1,3 @@
using System;
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo;
@ -24,4 +23,4 @@ public class ServiceTwo : IServiceTwo
/// <inheritdoc />
public override string ToString() => Helper.WriteMethodString(_clock, _id);
}
}

@ -1,12 +1,10 @@
using System;
using SmallInjectorDemo.Interfaces;
using SmallInjectorDemo.Interfaces;
namespace SmallInjectorDemo
namespace SmallInjectorDemo;
/// <inheritdoc />
public class SystemClock : IClock
{
/// <inheritdoc />
public class SystemClock : IClock
{
/// <inheritdoc />
public string CurrentDateTime => DateTime.Now.ToString("O");
}
}
public string CurrentDateTime => DateTime.Now.ToString("O");
}