Skip to content

Commit

Permalink
Moved TypeNameFormatter and more cleanup. All tests passed
Browse files Browse the repository at this point in the history
  • Loading branch information
seesharper committed Oct 27, 2024
1 parent a7ab501 commit 2f42bb7
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 85 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
"cSpell.words": [
"Callvirt",
"Castclass",
"Cloneable",
"Conv",
"decoratee",
"Initobj",
"Ldarg",
"Ldelem",
Expand All @@ -15,6 +17,7 @@
"Ldnull",
"Ldstr",
"MSIL",
"NETCOREAPP",
"Newarr",
"Newobj",
"Stelem",
Expand Down
6 changes: 2 additions & 4 deletions src/LightInject.Tests/ServiceRegistrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,13 @@ public void Register_ServiceAfterFirstGetInstance_TracesWarning()
{
string message = null;
var container = new ServiceContainer(new ContainerOptions { LogFactory = t => m => message = m.Message });

//SampleTraceListener sampleTraceListener = new SampleTraceListener(m => message = m);

try
{
/// Trace.Listeners.Add(sampleTraceListener);
container.Register<IFoo, Foo>();
container.GetInstance<IFoo>();
container.Register<IFoo, Foo>();
Assert.StartsWith("Cannot overwrite existing serviceregistration", message);
Assert.StartsWith("Cannot overwrite existing service registration", message);
}
finally
{
Expand Down
45 changes: 45 additions & 0 deletions src/LightInject.Tests/TypeNameFormatter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Text;

namespace LightInject;

/// <summary>
/// [assembly: DebuggerDisplay("{LightInject.TypeNameFormatter.GetHumanFriendlyTypeName(this)}", Target = typeof(Type))]
/// </summary>
public static class TypeNameFormatter
{
public static string GetHumanFriendlyTypeName(Type type)
{
StringBuilder humanFriendlyName = new StringBuilder();
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{

humanFriendlyName.Append(type.Name.Substring(0, type.Name.IndexOf('`')));
humanFriendlyName.Append('<');
foreach (Type argument in type.GenericTypeArguments)
{
humanFriendlyName.Append(GetHumanFriendlyTypeName(argument));
humanFriendlyName.Append(", ");
}
humanFriendlyName.Remove(humanFriendlyName.Length - 2, 2);
humanFriendlyName.Append('>');
}
else if (type.IsGenericTypeDefinition)
{
humanFriendlyName.Append(type.Name.Substring(0, type.Name.IndexOf('`')));
humanFriendlyName.Append('<');
foreach (Type parameter in type.GetGenericArguments())
{
humanFriendlyName.Append(parameter.Name);
humanFriendlyName.Append(", ");
}
humanFriendlyName.Remove(humanFriendlyName.Length - 2, 2);
humanFriendlyName.Append('>');
}
else
{
humanFriendlyName.Append(type.Name);
}
return humanFriendlyName.ToString();
}
}
112 changes: 31 additions & 81 deletions src/LightInject/LightInject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ LightInject version 7.0.0
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Performance")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("MaintainabilityRules", "SA1403", Justification = "One source file")]
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("DocumentationRules", "SA1649", Justification = "One source file")]
[assembly: DebuggerDisplay("{LightInject.TypeNameFormatter.GetHumanFriendlyTypeName(this)}", Target = typeof(Type))]

namespace LightInject
{
Expand Down Expand Up @@ -117,7 +116,7 @@ public enum FactoryType
/// <summary>
/// A factory that creates a service with runtime arguments.
/// </summary>
ServiceWithRuntimeArguments
ServiceWithRuntimeArguments,
}

/// <summary>
Expand Down Expand Up @@ -951,7 +950,7 @@ public interface ITypeConstructionInfoBuilder
}

/// <summary>
/// Represents a class that maps the generic arguments/parameters from a generic servicetype
/// Represents a class that maps the generic arguments/parameters from a generic service type
/// to a open generic implementing type.
/// </summary>
public interface IGenericArgumentMapper
Expand Down Expand Up @@ -2670,6 +2669,7 @@ public class ServiceContainer : IServiceContainer

private bool isLocked;
private Type defaultLifetimeType;
private int registrationOrder = 0;

/// <summary>
/// Initializes a new instance of the <see cref="ServiceContainer"/> class.
Expand Down Expand Up @@ -2918,9 +2918,6 @@ public IServiceRegistry RegisterFallback(Func<Type, string, bool> predicate, Fun
return this;
}

private int registrationOrder = 0;


/// <inheritdoc/>
public IServiceRegistry Register(ServiceRegistration serviceRegistration)
{
Expand All @@ -2929,6 +2926,7 @@ public IServiceRegistry Register(ServiceRegistration serviceRegistration)
{
serviceRegistration.Lifetime = DefaultLifetime;
}

var services = GetAvailableServices(serviceRegistration.ServiceType);
registrationOrder++;
serviceRegistration.RegistrationOrder = registrationOrder;
Expand Down Expand Up @@ -3360,7 +3358,6 @@ public IServiceRegistry RegisterOrdered(Type serviceType, ServiceRegistration[]
return this;
}


/// <inheritdoc/>
public void Compile(Func<ServiceRegistration, bool> predicate)
{
Expand Down Expand Up @@ -3527,6 +3524,7 @@ public void Dispose()
disposableObjects.Add(perContainerDisposable);
perContainerDisposable.Dispose();
}

foreach (var disposed in disposedObjects)
{
disposableObjects.Remove(disposed);
Expand Down Expand Up @@ -3962,7 +3960,6 @@ private Action<IEmitter> GetRegisteredEmitMethodWithoutMicrosoftCompatibility(Ty
return emitMethod ?? CreateEmitMethodForUnknownService(serviceType, serviceName);
}


private ServiceRegistration AddServiceRegistration(ServiceRegistration serviceRegistration)
{
var emitMethod = ResolveEmitMethod(serviceRegistration);
Expand All @@ -3984,7 +3981,7 @@ private ServiceRegistration UpdateServiceRegistration(ServiceRegistration existi
{
if (isLocked)
{
var message = $"Cannot overwrite existing serviceregistration {existingRegistration} after the first call to GetInstance.";
var message = $"Cannot overwrite existing service registration {existingRegistration} after the first call to GetInstance.";
log.Warning(message);
return existingRegistration;
}
Expand Down Expand Up @@ -4290,9 +4287,6 @@ private Action<IEmitter> GetEmitMethodForDependency(Dependency dependency)
emitter.PushConstant(serviceKeyConverterIndex, typeof(IServiceKeyConverter));
emitter.Emit(OpCodes.Ldstr, dependency.ConstructionInfo.ServiceName);
emitter.Emit(OpCodes.Callvirt, closedGenericConvertServiceKeyMethod);

// emitter.Emit(OpCodes.Ldarg_0);
// emitter.Emit(OpCodes.Call, RuntimeArgumentsLoader.LoadServiceNameMethod);
};
}

Expand Down Expand Up @@ -5100,7 +5094,7 @@ private void EmitLifetime(ServiceRegistration serviceRegistration, Action<IEmitt

emitter.Emit(OpCodes.Call, ScopeLoader.ValidateScopeMethod.MakeGenericMethod(serviceRegistration.ServiceType.UnderlyingSystemType));

// Push the getinstance delegate
// Push the getInstance delegate
emitter.PushConstant(instanceDelegateIndex, typeof(GetInstanceDelegate));

emitter.PushArgument(0);
Expand Down Expand Up @@ -6535,7 +6529,7 @@ public class ServiceRegistration : Registration
/// Gets or sets the value that represents the instance of the service.
/// </summary>
public object Value { get; set; }

/// <summary>
/// Gets or sets the service registration order.
/// </summary>
Expand Down Expand Up @@ -6711,6 +6705,9 @@ public ConstructionInfo()
/// </summary>
public Delegate FactoryDelegate { get; set; }

/// <summary>
/// Gets or sets the service name the service that this <see cref="ConstructionInfo"/> represents.
/// </summary>
public string ServiceName { get; set; }
}

Expand Down Expand Up @@ -6745,13 +6742,15 @@ public abstract class Dependency
public bool IsRequired { get; set; }

/// <summary>
/// Gets or sets a bool value that indicates if this parameter represents the service key/name.
/// Gets or sets a value indicating whether this parameter represents the service key/name.
/// </summary>
public bool IsServiceKey { get; set; }

/// <summary>
/// Gets or sets the <see cref="ConstructionInfo"/> that represents the construction information.
/// </summary>
public ConstructionInfo ConstructionInfo { get; set; }


/// <summary>
/// Returns textual information about the dependency.
/// </summary>
Expand Down Expand Up @@ -7082,6 +7081,7 @@ public void TrackInstance(object disposable)
{
return;
}

lock (lockObject)
{
if (disposableObjects == null)
Expand Down Expand Up @@ -7120,6 +7120,7 @@ public void Dispose()

EndScope();
}

#if USE_ASYNCDISPOSABLE
/// <inheritdoc/>
public ValueTask DisposeAsync()
Expand Down Expand Up @@ -7181,6 +7182,7 @@ static async ValueTask Await(int i, ValueTask vt, List<object> toDispose, HashSe
{
continue;
}

if (objectToDispose is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
Expand All @@ -7193,15 +7195,8 @@ static async ValueTask Await(int i, ValueTask vt, List<object> toDispose, HashSe
}
}
#endif
private void EndScope()
{
scopeManager?.EndScope(this);
var completedHandler = Completed;
completedHandler?.Invoke(this, new EventArgs());
IsDisposed = true;
}

/// <inheritdoc/>
/// <inheritdoc/>
public Scope BeginScope() => serviceFactory.BeginScope();

/// <inheritdoc/>
Expand Down Expand Up @@ -7250,9 +7245,9 @@ internal object GetScopedInstance(GetInstanceDelegate getInstanceDelegate, objec
if (createdInstance == null)
{
createdInstance = getInstanceDelegate(arguments, this);
#if USE_ASYNCDISPOSABLE
#if USE_ASYNCDISPOSABLE
if (createdInstance is IDisposable || createdInstance is IAsyncDisposable)
#else
#else
if (createdInstance is IDisposable)
#endif
{
Expand All @@ -7266,6 +7261,14 @@ internal object GetScopedInstance(GetInstanceDelegate getInstanceDelegate, objec
}
}

private void EndScope()
{
scopeManager?.EndScope(this);
var completedHandler = Completed;
completedHandler?.Invoke(this, new EventArgs());
IsDisposed = true;
}

private class ReferenceEqualityComparer<T> : IEqualityComparer<T>
{
public static readonly ReferenceEqualityComparer<T> Default
Expand Down Expand Up @@ -7551,7 +7554,7 @@ public void Execute<TCompositionRoot>(TCompositionRoot compositionRoot)
}

/// <summary>
/// A class that maps the generic arguments/parameters from a generic servicetype
/// A class that maps the generic arguments/parameters from a generic service type
/// to a open generic implementing type.
/// </summary>
public class GenericArgumentMapper : IGenericArgumentMapper
Expand All @@ -7565,9 +7568,6 @@ public class GenericArgumentMapper : IGenericArgumentMapper
/// <returns>A <see cref="GenericMappingResult"/>.</returns>
public GenericMappingResult Map(Type genericServiceType, Type openGenericImplementingType)
{
// string[] genericParameterNames = GetGenericArgumentsOrParameters(genericServiceType).Select(t => t.Name).ToArray();


string[] genericParameterNames =
openGenericImplementingType.GetTypeInfo().GenericTypeParameters.Select(t => t.Name).ToArray();

Expand Down Expand Up @@ -8452,8 +8452,6 @@ public class Emitter : IEmitter

private readonly List<Instruction> instructions = new List<Instruction>();

private string serviceKey;

/// <summary>
/// Initializes a new instance of the <see cref="Emitter"/> class.
/// </summary>
Expand All @@ -8465,16 +8463,6 @@ public Emitter(ILGenerator generator, Type[] parameterTypes)
this.parameterTypes = parameterTypes;
}

public void SetServiceKey(string serviceKey)
{
this.serviceKey = serviceKey;
}

public string GetServiceKey()
{
return serviceKey;
}

/// <inheritdoc/>
public Type StackType => stack.Count == 0 ? null : stack.Peek();

Expand Down Expand Up @@ -9272,45 +9260,7 @@ private static Type CreateEnumerableType(Type type) =>
typeof(IEnumerable<>).MakeGenericType(type);
}

public static class TypeNameFormatter
{
public static string GetHumanFriendlyTypeName(Type type)
{
StringBuilder humanFriendlyName = new StringBuilder();
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{

humanFriendlyName.Append(type.Name.Substring(0, type.Name.IndexOf('`')));
humanFriendlyName.Append('<');
foreach (Type argument in type.GenericTypeArguments)
{
humanFriendlyName.Append(GetHumanFriendlyTypeName(argument));
humanFriendlyName.Append(", ");
}
humanFriendlyName.Remove(humanFriendlyName.Length - 2, 2);
humanFriendlyName.Append('>');
}
else if (type.IsGenericTypeDefinition)
{
humanFriendlyName.Append(type.Name.Substring(0, type.Name.IndexOf('`')));
humanFriendlyName.Append('<');
foreach (Type parameter in type.GetGenericArguments())
{
humanFriendlyName.Append(parameter.Name);
humanFriendlyName.Append(", ");
}
humanFriendlyName.Remove(humanFriendlyName.Length - 2, 2);
humanFriendlyName.Append('>');
}
else
{
humanFriendlyName.Append(type.Name);
}
return humanFriendlyName.ToString();
}
}

internal class EmitMethodInfo
internal class EmitMethodInfo
{
public EmitMethodInfo(Type serviceType, Action<IEmitter> emitMethod, int registrationOrder, bool createdFromWildCardService)
{
Expand Down

0 comments on commit 2f42bb7

Please sign in to comment.