diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js
index b465a443..39ff5c5e 100644
--- a/docs/.vitepress/config.js
+++ b/docs/.vitepress/config.js
@@ -42,13 +42,7 @@ module.exports = {
collapsible: true,
collapsed: true,
items: getIOCSideBar()
- },
- {
- text: 'Compilation',
- collapsible: true,
- collapsed: true,
- items: getCompilationSideBar()
- },
+ }
]
}
@@ -230,37 +224,3 @@ function getIOCSideBar() {
]
}
-function getCompilationSideBar() {
- return [
- {
- text: 'Compiling code with AssemblyGenerator',
- link: '/guide/compilation/assembly-generator'
- },
- {
- text: 'Generating code with ISourceWriter',
- link: '/guide/compilation/source-writer'
- },
- {
- text: 'The "Frame" Model',
- link: '/guide/compilation/frames/',
- children: [
- {
- text: 'Working with Variables',
- link: '/guide/compilation/frames/variables'
- },
- {
- text: 'Building custom Frames',
- link: '/guide/compilation/frames/frame'
- },
- {
- text: 'Extension methods for Names in code',
- link: '/guide/compilation/frames/extension-methods'
- },
- {
- text: 'Injected Fields',
- link: '/guide/compilation/frames/injected-fields'
- },
- ]
- }
- ]
-}
diff --git a/src/Lamar.AspNetCoreTests/Lamar.AspNetCoreTests.csproj b/src/Lamar.AspNetCoreTests/Lamar.AspNetCoreTests.csproj
index 6808ac48..683a8db6 100644
--- a/src/Lamar.AspNetCoreTests/Lamar.AspNetCoreTests.csproj
+++ b/src/Lamar.AspNetCoreTests/Lamar.AspNetCoreTests.csproj
@@ -10,6 +10,7 @@
+
@@ -26,11 +27,11 @@
-
+
-
+
diff --git a/src/Lamar.AspNetCoreTests/integrating_with_HostBuilder.cs b/src/Lamar.AspNetCoreTests/integrating_with_HostBuilder.cs
index 4c33e095..00505936 100644
--- a/src/Lamar.AspNetCoreTests/integrating_with_HostBuilder.cs
+++ b/src/Lamar.AspNetCoreTests/integrating_with_HostBuilder.cs
@@ -3,9 +3,8 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using Baseline;
+using JasperFx.Core;
using Lamar.Microsoft.DependencyInjection;
-using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
diff --git a/src/Lamar.AspNetCoreTests/integration_with_aspnetcore.cs b/src/Lamar.AspNetCoreTests/integration_with_aspnetcore.cs
index 57f06abd..3053a811 100644
--- a/src/Lamar.AspNetCoreTests/integration_with_aspnetcore.cs
+++ b/src/Lamar.AspNetCoreTests/integration_with_aspnetcore.cs
@@ -6,9 +6,9 @@
using System.Threading;
using System.Threading.Tasks;
using App.Metrics.AspNetCore;
-using Baseline;
using IdentityServer4.Models;
-using JasperFx.CodeGeneration;
+using JasperFx.Core;
+using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
using Lamar.Microsoft.DependencyInjection;
using Microsoft.AspNetCore.Builder;
diff --git a/src/Lamar.Diagnostics/Lamar.Diagnostics.csproj b/src/Lamar.Diagnostics/Lamar.Diagnostics.csproj
index 1445aa16..aa2ba9fa 100644
--- a/src/Lamar.Diagnostics/Lamar.Diagnostics.csproj
+++ b/src/Lamar.Diagnostics/Lamar.Diagnostics.csproj
@@ -2,7 +2,7 @@
Adds diagnostic checks to the command line of your Lamar-enabled ASP.Net Core app
- 11.1.4
+ 12.0.0
Jeremy D. Miller
net6.0;net7.0
portable
diff --git a/src/Lamar.Microsoft.DependencyInjection/Lamar.Microsoft.DependencyInjection.csproj b/src/Lamar.Microsoft.DependencyInjection/Lamar.Microsoft.DependencyInjection.csproj
index 52a4dc4d..abaae1f6 100644
--- a/src/Lamar.Microsoft.DependencyInjection/Lamar.Microsoft.DependencyInjection.csproj
+++ b/src/Lamar.Microsoft.DependencyInjection/Lamar.Microsoft.DependencyInjection.csproj
@@ -1,7 +1,7 @@
Lamar Adapter for HostBuilder Integration
- 11.1.4
+ 12.0.0
Jeremy D. Miller
net6.0;net7.0
portable
diff --git a/src/Lamar.Testing/Examples/SetterExamples.cs b/src/Lamar.Testing/Examples/SetterExamples.cs
index 4dadfc49..65e5ad3a 100644
--- a/src/Lamar.Testing/Examples/SetterExamples.cs
+++ b/src/Lamar.Testing/Examples/SetterExamples.cs
@@ -1,6 +1,6 @@
using System;
using System.Reflection;
-using JasperFx.TypeDiscovery;
+using JasperFx.Core.TypeScanning;
using Lamar.Scanning.Conventions;
using Shouldly;
using StructureMap.Testing.Widget;
diff --git a/src/Lamar.Testing/IoC/Acceptance/custom_registration_convention.cs b/src/Lamar.Testing/IoC/Acceptance/custom_registration_convention.cs
index 4810715d..3b020828 100644
--- a/src/Lamar.Testing/IoC/Acceptance/custom_registration_convention.cs
+++ b/src/Lamar.Testing/IoC/Acceptance/custom_registration_convention.cs
@@ -1,5 +1,5 @@
using System.Linq;
-using JasperFx.TypeDiscovery;
+using JasperFx.Core.TypeScanning;
using Lamar.Scanning.Conventions;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
diff --git a/src/Lamar.Testing/IoC/Acceptance/missing_instance_requests.cs b/src/Lamar.Testing/IoC/Acceptance/missing_instance_requests.cs
index 158b1c6f..8a865801 100644
--- a/src/Lamar.Testing/IoC/Acceptance/missing_instance_requests.cs
+++ b/src/Lamar.Testing/IoC/Acceptance/missing_instance_requests.cs
@@ -1,4 +1,5 @@
using JasperFx.CodeGeneration;
+using JasperFx.Core.Reflection;
using Lamar.IoC;
using Shouldly;
using StructureMap.Testing.Widget;
diff --git a/src/Lamar/AssemblyInfo.cs b/src/Lamar/AssemblyInfo.cs
index d046b448..8a17ea72 100644
--- a/src/Lamar/AssemblyInfo.cs
+++ b/src/Lamar/AssemblyInfo.cs
@@ -3,4 +3,4 @@
[assembly: InternalsVisibleTo("Lamar.Testing")]
[assembly: InternalsVisibleTo("Lamar.Diagnostics")]
-[assembly:IgnoreAssembly]
\ No newline at end of file
+[assembly: IgnoreAssembly]
\ No newline at end of file
diff --git a/src/Lamar/Container.cs b/src/Lamar/Container.cs
index e09749e5..649971dd 100644
--- a/src/Lamar/Container.cs
+++ b/src/Lamar/Container.cs
@@ -5,180 +5,244 @@
using System.Threading.Tasks;
using JasperFx.Core.Reflection;
using Lamar.IoC;
-using JasperFx.CodeGeneration;
-using JasperFx.CodeGeneration.Util;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar
+namespace Lamar;
+
+#region sample_Container-Declaration
+
+public class Container : Scope, IContainer, INestedContainer, IServiceScopeFactory, IServiceScope,
+ ISupportRequiredService
+
+ #endregion
+
{
- #region sample_Container-Declaration
- public class Container : Scope, IContainer, INestedContainer, IServiceScopeFactory, IServiceScope,
- ISupportRequiredService
+ private bool _isDisposing;
+ private Container()
+ {
+ }
- #endregion
+ public Container(IServiceCollection services) : base(services)
{
- private bool _isDisposing;
+ }
- private Container()
- {
- }
+ public Container(Action configuration) : this(ServiceRegistry.For(configuration))
+ {
+ }
+
+ private Container(ServiceGraph serviceGraph, Container container) : base(serviceGraph, container)
+ {
+ }
- public Container(IServiceCollection services) : base(services)
+ public INestedContainer GetNestedContainer()
+ {
+ assertNotDisposed();
+ return new Container(ServiceGraph, this);
+ }
+
+ public override void Dispose()
+ {
+ // Because a StackOverflowException when trying to cleanly shut down
+ // an application is really no fun
+ if (_isDisposing)
{
+ return;
}
- public Container(Action configuration) : this(ServiceRegistry.For(configuration))
+ _isDisposing = true;
+
+ base.Dispose();
+
+ if (ReferenceEquals(Root, this))
{
+ ServiceGraph.Dispose();
}
+ }
- private Container(ServiceGraph serviceGraph, Container container) : base(serviceGraph, container)
+ public override async ValueTask DisposeAsync()
+ {
+ // Because a StackOverflowException when trying to cleanly shut down
+ // an application is really no fun
+ if (_isDisposing)
{
+ return;
}
- public INestedContainer GetNestedContainer()
+ _isDisposing = true;
+
+ await base.DisposeAsync();
+
+ if (ReferenceEquals(Root, this))
{
- assertNotDisposed();
- return new Container(ServiceGraph, this);
+ await ServiceGraph.DisposeAsync();
}
+ }
- public override void Dispose()
- {
- // Because a StackOverflowException when trying to cleanly shut down
- // an application is really no fun
- if (_isDisposing) return;
- _isDisposing = true;
+ public void AssertConfigurationIsValid(AssertMode mode = AssertMode.Full)
+ {
+ using (var writer = new StringWriter())
+ {
+ var hasErrors = validateConfiguration(writer);
- base.Dispose();
+ if (!hasErrors && mode == AssertMode.Full)
+ {
+ hasErrors = buildAndValidateAll(writer);
+ }
- if (ReferenceEquals(Root, this)) ServiceGraph.Dispose();
+ if (hasErrors)
+ {
+ throw new ContainerValidationException(writer.ToString(), WhatDoIHave(), WhatDidIScan());
+ }
}
+ }
- public override async ValueTask DisposeAsync()
+ ///
+ /// Add additional configurations to this container. NOT RECOMMENDED.
+ ///
+ ///
+ ///
+ public void Configure(IServiceCollection services)
+ {
+ if (services.Any(x => x.ServiceType == typeof(IFamilyPolicy)))
{
- // Because a StackOverflowException when trying to cleanly shut down
- // an application is really no fun
- if (_isDisposing) return;
-
- _isDisposing = true;
-
- await base.DisposeAsync();
+ throw new InvalidOperationException("Cannot register any IFamilyPolicy objects in Configure()");
+ }
- if (ReferenceEquals(Root, this)) await ServiceGraph.DisposeAsync();
+ if (services.Any(x => x.ServiceType == typeof(IFamilyPolicy)))
+ {
+ throw new InvalidOperationException("Cannot register any IFamilyPolicy objects in Configure()");
}
+ ServiceGraph.AppendServices(services);
+ }
- public void AssertConfigurationIsValid(AssertMode mode = AssertMode.Full)
+ ///
+ /// Add additional configurations to this container. NOT RECOMMENDED.
+ ///
+ ///
+ public void Configure(Action configure)
+ {
+ if (!ReferenceEquals(this, Root))
{
- using (var writer = new StringWriter())
- {
- var hasErrors = validateConfiguration(writer);
+ throw new InvalidOperationException("Configure() cannot be used with nested containers");
+ }
- if (!hasErrors && mode == AssertMode.Full) hasErrors = buildAndValidateAll(writer);
+ var services = new ServiceRegistry();
+ configure(services);
- if (hasErrors)
- {
- throw new ContainerValidationException(writer.ToString(), WhatDoIHave(), WhatDidIScan());
- }
- }
- }
+ Configure(services);
+ }
- ///
- /// Add additional configurations to this container. NOT RECOMMENDED.
- ///
- ///
- ///
- public void Configure(IServiceCollection services)
- {
- if (services.Any(x => x.ServiceType == typeof(IFamilyPolicy)))
- throw new InvalidOperationException("Cannot register any IFamilyPolicy objects in Configure()");
- if (services.Any(x => x.ServiceType == typeof(IFamilyPolicy)))
- throw new InvalidOperationException("Cannot register any IFamilyPolicy objects in Configure()");
- ServiceGraph.AppendServices(services);
- }
+ IServiceScope IServiceScopeFactory.CreateScope()
+ {
+ return (IServiceScope)GetNestedContainer();
+ }
- ///
- /// Add additional configurations to this container. NOT RECOMMENDED.
- ///
- ///
- public void Configure(Action configure)
- {
- if (!ReferenceEquals(this, Root))
- throw new InvalidOperationException("Configure() cannot be used with nested containers");
- var services = new ServiceRegistry();
- configure(services);
+ object ISupportRequiredService.GetRequiredService(Type serviceType)
+ {
+ return GetInstance(serviceType);
+ }
- Configure(services);
- }
+ public new static Container Empty()
+ {
+ return For(_ => { });
+ }
+ public static Container For() where T : ServiceRegistry, new()
+ {
+ return new Container(new T());
+ }
- IServiceScope IServiceScopeFactory.CreateScope()
- {
- return (IServiceScope) GetNestedContainer();
- }
+ public static Container For(Action configuration)
+ {
+ var registry = new ServiceRegistry();
+ configuration(registry);
+ return new Container(registry);
+ }
- object ISupportRequiredService.GetRequiredService(Type serviceType)
- {
- return GetInstance(serviceType);
- }
+ public static Task BuildAsync(Action configure)
+ {
+ var services = new ServiceRegistry();
+ configure(services);
- public new static Container Empty()
- {
- return For(_ => { });
- }
+ return BuildAsync(services);
+ }
- public static Container For() where T : ServiceRegistry, new()
- {
- return new Container(new T());
- }
+ public static async Task BuildAsync(IServiceCollection services)
+ {
+ var container = new Container();
- public static Container For(Action configuration)
- {
- var registry = new ServiceRegistry();
- configuration(registry);
+ var graph = await ServiceGraph.BuildAsync(services, container);
- return new Container(registry);
- }
+ container.Root = container;
+ container.ServiceGraph = graph;
- public static Task BuildAsync(Action configure)
- {
- var services = new ServiceRegistry();
- configure(services);
+ graph.Initialize();
- return BuildAsync(services);
- }
+ return container;
+ }
- public static async Task BuildAsync(IServiceCollection services)
- {
- var container = new Container();
+ private bool buildAndValidateAll(StringWriter writer)
+ {
+ var hasErrors = false;
- var graph = await ServiceGraph.BuildAsync(services, container);
+ foreach (var instance in Model.AllInstances.Where(x =>
+ x.Lifetime == ServiceLifetime.Singleton && !x.ServiceType.IsOpenGeneric()))
+ {
+ try
+ {
+ Debug.WriteLine($"Trying to resolve {instance.ServiceType.FullNameInCode()}");
+ var o = instance.Instance.Resolve(this);
- container.Root = container;
- container.ServiceGraph = graph;
-
- graph.Initialize();
+ if (o != null)
+ {
+ foreach (var method in ValidationMethodAttribute.GetValidationMethods(o.GetType()))
+ {
+ try
+ {
+ method.Invoke(o, new object[0]);
+ }
+ catch (Exception e)
+ {
+ hasErrors = true;
+
+ writer.WriteLine($"Error in {o.GetType().FullNameInCode()}.{method.Name}()");
+ writer.WriteLine(e.ToString());
+ writer.WriteLine();
+ writer.WriteLine();
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ hasErrors = true;
- return container;
+ writer.WriteLine("Error in " + instance);
+ writer.WriteLine(e.ToString());
+ writer.WriteLine();
+ writer.WriteLine();
+ }
}
- private bool buildAndValidateAll(StringWriter writer)
+ using (var scope = new Scope(ServiceGraph, this))
{
- var hasErrors = false;
-
foreach (var instance in Model.AllInstances.Where(x =>
- x.Lifetime == ServiceLifetime.Singleton && !x.ServiceType.IsOpenGeneric()))
+ x.Lifetime != ServiceLifetime.Singleton && !x.ServiceType.IsOpenGeneric()))
+ {
try
{
- Debug.WriteLine($"Trying to resolve {instance.ServiceType.FullNameInCode()}");
var o = instance.Instance.Resolve(this);
if (o != null)
+ {
foreach (var method in ValidationMethodAttribute.GetValidationMethods(o.GetType()))
+ {
try
{
method.Invoke(o, new object[0]);
@@ -192,6 +256,8 @@ private bool buildAndValidateAll(StringWriter writer)
writer.WriteLine();
writer.WriteLine();
}
+ }
+ }
}
catch (Exception e)
{
@@ -202,72 +268,38 @@ private bool buildAndValidateAll(StringWriter writer)
writer.WriteLine();
writer.WriteLine();
}
-
- using (var scope = new Scope(ServiceGraph, this))
- {
- foreach (var instance in Model.AllInstances.Where(x =>
- x.Lifetime != ServiceLifetime.Singleton && !x.ServiceType.IsOpenGeneric()))
- try
- {
- var o = instance.Instance.Resolve(this);
-
- if (o != null)
- foreach (var method in ValidationMethodAttribute.GetValidationMethods(o.GetType()))
- try
- {
- method.Invoke(o, new object[0]);
- }
- catch (Exception e)
- {
- hasErrors = true;
-
- writer.WriteLine($"Error in {o.GetType().FullNameInCode()}.{method.Name}()");
- writer.WriteLine(e.ToString());
- writer.WriteLine();
- writer.WriteLine();
- }
- }
- catch (Exception e)
- {
- hasErrors = true;
-
- writer.WriteLine("Error in " + instance);
- writer.WriteLine(e.ToString());
- writer.WriteLine();
- writer.WriteLine();
- }
}
-
- return hasErrors;
}
- private bool validateConfiguration(StringWriter writer)
- {
- var invalids = Model.AllInstances.Where(x => x.Instance.ErrorMessages.Any()).ToArray();
+ return hasErrors;
+ }
- if (!invalids.Any()) return false;
+ private bool validateConfiguration(StringWriter writer)
+ {
+ var invalids = Model.AllInstances.Where(x => x.Instance.ErrorMessages.Any()).ToArray();
+ if (!invalids.Any())
+ {
+ return false;
+ }
- foreach (var instance in invalids)
- {
- writer.WriteLine(instance);
- foreach (var message in instance.Instance.ErrorMessages) writer.WriteLine(message);
- writer.WriteLine();
- writer.WriteLine();
- }
+ foreach (var instance in invalids)
+ {
+ writer.WriteLine(instance);
+ foreach (var message in instance.Instance.ErrorMessages) writer.WriteLine(message);
- return true;
+ writer.WriteLine();
+ writer.WriteLine();
}
-
-
+ return true;
}
+}
- ///
- /// Use internally by Lamar
- ///
- public interface IStub
- {
- }
+///
+/// Use internally by Lamar
+///
+public interface IStub
+{
}
\ No newline at end of file
diff --git a/src/Lamar/DefaultConstructorAttribute.cs b/src/Lamar/DefaultConstructorAttribute.cs
index 83b807e8..584e76d2 100644
--- a/src/Lamar/DefaultConstructorAttribute.cs
+++ b/src/Lamar/DefaultConstructorAttribute.cs
@@ -2,37 +2,36 @@
using System.Linq;
using System.Reflection;
-namespace Lamar
+namespace Lamar;
+
+///
+/// Used to override the constructor of a class to be used by StructureMap to create
+/// a Pluggable object
+///
+[AttributeUsage(AttributeTargets.Constructor)]
+public class DefaultConstructorAttribute : Attribute
{
///
- /// Used to override the constructor of a class to be used by StructureMap to create
- /// a Pluggable object
+ /// Examines a System.Type object and determines the ConstructorInfo to use in creating
+ /// instances of the Type
///
- [AttributeUsage(AttributeTargets.Constructor)]
- public class DefaultConstructorAttribute : Attribute
+ ///
+ ///
+ public static ConstructorInfo GetConstructor(Type exportedType)
{
- ///
- /// Examines a System.Type object and determines the ConstructorInfo to use in creating
- /// instances of the Type
- ///
- ///
- ///
- public static ConstructorInfo GetConstructor(Type exportedType)
+ ConstructorInfo returnValue = null;
+
+ foreach (var constructor in exportedType.GetConstructors())
{
- ConstructorInfo returnValue = null;
+ var atts = constructor.GetCustomAttributes(typeof(DefaultConstructorAttribute), true);
- foreach (var constructor in exportedType.GetConstructors())
+ if (atts.Any())
{
- var atts = constructor.GetCustomAttributes(typeof (DefaultConstructorAttribute), true);
-
- if (atts.Any())
- {
- returnValue = constructor;
- break;
- }
+ returnValue = constructor;
+ break;
}
-
- return returnValue;
}
+
+ return returnValue;
}
}
\ No newline at end of file
diff --git a/src/Lamar/Diagnostics/IModel.cs b/src/Lamar/Diagnostics/IModel.cs
index 1845a2b5..27fba6bd 100644
--- a/src/Lamar/Diagnostics/IModel.cs
+++ b/src/Lamar/Diagnostics/IModel.cs
@@ -3,100 +3,98 @@
using Lamar.IoC.Instances;
using Lamar.Scanning.Conventions;
-namespace Lamar.Diagnostics
+namespace Lamar.Diagnostics;
+
+///
+/// Can be used to analyze and query the registrations and configuration
+/// of the running Container or Scope
+///
+public interface IModel
{
///
- /// Can be used to analyze and query the registrations and configuration
- /// of the running Container or Scope
+ /// Access to all the Service Type registrations
+ ///
+ IEnumerable ServiceTypes { get; }
+
+ ///
+ /// All explicitly known Instance's in this container. Other instances can be created during
+ /// the lifetime of the container
///
- public interface IModel
- {
- ///
- /// Retrieves the configuration for the given type
- ///
- ///
- ///
- IServiceFamilyConfiguration For();
+ IEnumerable AllInstances { get; }
- ///
- /// Retrieves the configuration for the given type
- ///
- ///
- ///
- IServiceFamilyConfiguration For(Type type);
+ ///
+ /// All of the assembly scanning operations that were used to build this
+ /// Container
+ ///
+ IEnumerable Scanners { get; }
- ///
- /// Access to all the Service Type registrations
- ///
- IEnumerable ServiceTypes { get; }
+ ///
+ /// Retrieves the configuration for the given type
+ ///
+ ///
+ ///
+ IServiceFamilyConfiguration For();
- ///
- /// Queryable access to all of the Instance for a given ServiceType
- ///
- ///
- ///
- IEnumerable InstancesOf(Type serviceType);
+ ///
+ /// Retrieves the configuration for the given type
+ ///
+ ///
+ ///
+ IServiceFamilyConfiguration For(Type type);
- ///
- /// Queryable access to all of the Instance for a given ServiceType
- ///
- ///
- IEnumerable InstancesOf();
+ ///
+ /// Queryable access to all of the Instance for a given ServiceType
+ ///
+ ///
+ ///
+ IEnumerable InstancesOf(Type serviceType);
- ///
- /// Find the concrete type for the default Instance of T.
- /// In other words, when I call Container.GetInstance(Type),
- /// what do I get? May be indeterminate
- ///
- ///
- ///
- Type DefaultTypeFor();
+ ///
+ /// Queryable access to all of the Instance for a given ServiceType
+ ///
+ ///
+ IEnumerable InstancesOf();
- ///
- /// Find the concrete type for the default Instance of pluginType.
- /// In other words, when I call Container.GetInstance(Type),
- /// what do I get? May be indeterminate
- ///
- ///
- Type DefaultTypeFor(Type serviceType);
-
- ///
- /// All explicitly known Instance's in this container. Other instances can be created during
- /// the lifetime of the container
- ///
- IEnumerable AllInstances { get; }
+ ///
+ /// Find the concrete type for the default Instance of T.
+ /// In other words, when I call Container.GetInstance(Type),
+ /// what do I get? May be indeterminate
+ ///
+ ///
+ ///
+ Type DefaultTypeFor();
- ///
- /// Get each and every configured instance that could possibly
- /// be cast to T
- ///
- ///
- ///
- T[] GetAllPossible() where T : class;
-
- ///
- /// Can Lamar fulfill a request to ObjectFactory.GetInstance(pluginType) from the
- /// current configuration. This does not include concrete classes that could be auto-configured
- /// upon demand
- ///
- ///
- ///
- bool HasRegistrationFor(Type serviceType);
+ ///
+ /// Find the concrete type for the default Instance of pluginType.
+ /// In other words, when I call Container.GetInstance(Type),
+ /// what do I get? May be indeterminate
+ ///
+ ///
+ Type DefaultTypeFor(Type serviceType);
- ///
- /// Can Lamar fulfill a request to ObjectFactory.GetInstance<T>() from the
- /// current configuration. This does not include concrete classes that could be auto-configured
- /// upon demand
- ///
- ///
- ///
- bool HasRegistrationFor();
+ ///
+ /// Get each and every configured instance that could possibly
+ /// be cast to T
+ ///
+ ///
+ ///
+ T[] GetAllPossible() where T : class;
- ///
- /// All of the assembly scanning operations that were used to build this
- /// Container
- ///
- IEnumerable Scanners { get; }
+ ///
+ /// Can Lamar fulfill a request to ObjectFactory.GetInstance(pluginType) from the
+ /// current configuration. This does not include concrete classes that could be auto-configured
+ /// upon demand
+ ///
+ ///
+ ///
+ bool HasRegistrationFor(Type serviceType);
- }
+ ///
+ /// Can Lamar fulfill a request to ObjectFactory.GetInstance<T>() from the
+ /// current configuration. This does not include concrete classes that could be auto-configured
+ /// upon demand
+ ///
+ ///
+ ///
+ bool HasRegistrationFor();
}
\ No newline at end of file
diff --git a/src/Lamar/Diagnostics/InstanceRef.cs b/src/Lamar/Diagnostics/InstanceRef.cs
index 4bd57419..a22f8fc9 100644
--- a/src/Lamar/Diagnostics/InstanceRef.cs
+++ b/src/Lamar/Diagnostics/InstanceRef.cs
@@ -2,103 +2,100 @@
using JasperFx.Core;
using Lamar.IoC;
using Lamar.IoC.Instances;
-using Lamar.Util;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.Diagnostics
+namespace Lamar.Diagnostics;
+
+///
+/// A diagnostic wrapper around registered Instance's
+///
+public class InstanceRef
{
- ///
- /// A diagnostic wrapper around registered Instance's
- ///
- public class InstanceRef
- {
- private readonly Scope _rootScope;
- private readonly Scope _scope;
+ private readonly Scope _rootScope;
+ private readonly Scope _scope;
- public InstanceRef(Instance instance, Scope scope)
- {
- Instance = instance;
- _scope = scope;
- _rootScope = scope.Root;
- }
+ public InstanceRef(Instance instance, Scope scope)
+ {
+ Instance = instance;
+ _scope = scope;
+ _rootScope = scope.Root;
+ }
- ///
- /// The underlying Lamar model for building this configured Instance. ACCESS THIS WITH CAUTION!
- ///
- public Instance Instance { get; }
+ ///
+ /// The underlying Lamar model for building this configured Instance. ACCESS THIS WITH CAUTION!
+ ///
+ public Instance Instance { get; }
- ///
- /// The lifecycle of this specific Instance
- ///
- public ServiceLifetime Lifetime => Instance.Lifetime;
+ ///
+ /// The lifecycle of this specific Instance
+ ///
+ public ServiceLifetime Lifetime => Instance.Lifetime;
- public string Name => Instance.Name;
+ public string Name => Instance.Name;
- ///
- /// The actual concrete type of this Instance. Not every type of IInstance
- /// can determine the ConcreteType
- ///
- public Type ImplementationType => Instance.ImplementationType;
+ ///
+ /// The actual concrete type of this Instance. Not every type of IInstance
+ /// can determine the ConcreteType
+ ///
+ public Type ImplementationType => Instance.ImplementationType;
+ public Type ServiceType => Instance.ServiceType;
- public Type ServiceType => Instance.ServiceType;
+ ///
+ /// Returns the real object represented by this Instance
+ /// resolved by the underlying Container
+ ///
+ ///
+ ///
+ public T Get() where T : class
+ {
+ return Resolve() as T;
+ }
- ///
- /// Returns the real object represented by this Instance
- /// resolved by the underlying Container
- ///
- ///
- ///
- public T Get() where T : class
+ ///
+ /// Has the object already been created and
+ /// cached in its Lifetime? Mostly useful
+ /// for Singleton's
+ ///
+ ///
+ public bool ObjectHasBeenCreated()
+ {
+ switch (Lifetime)
{
- return Resolve() as T;
+ case ServiceLifetime.Transient:
+ return false;
+ case ServiceLifetime.Scoped:
+ return _scope.Services.TryFind(Instance.Hash, out var _);
+ case ServiceLifetime.Singleton:
+ return _scope.Root.Services.TryFind(Instance.Hash, out var _);
}
- ///
- /// Has the object already been created and
- /// cached in its Lifetime? Mostly useful
- /// for Singleton's
- ///
- ///
- public bool ObjectHasBeenCreated()
- {
- switch (Lifetime)
- {
- case ServiceLifetime.Transient:
- return false;
- case ServiceLifetime.Scoped:
- return _scope.Services.TryFind(Instance.Hash, out var _);
- case ServiceLifetime.Singleton:
- return _scope.Root.Services.TryFind(Instance.Hash, out var _);
- }
-
- return false;
- }
+ return false;
+ }
- ///
- /// Creates the textual representation of the 'BuildPlan'
- /// for this Instance
- ///
- ///
- public string DescribeBuildPlan()
- {
- return Instance.GetBuildPlan(_rootScope);
- }
+ ///
+ /// Creates the textual representation of the 'BuildPlan'
+ /// for this Instance
+ ///
+ ///
+ public string DescribeBuildPlan()
+ {
+ return Instance.GetBuildPlan(_rootScope);
+ }
- ///
- /// Builds or resolves an object instance for this registration
- ///
- ///
- public object Resolve()
- {
- return Instance.Resolve(_scope);
- }
+ ///
+ /// Builds or resolves an object instance for this registration
+ ///
+ ///
+ public object Resolve()
+ {
+ return Instance.Resolve(_scope);
+ }
- public override string ToString()
- {
- return Instance.ToString();
- }
+ public override string ToString()
+ {
+ return Instance.ToString();
}
}
\ No newline at end of file
diff --git a/src/Lamar/Diagnostics/QueryModel.cs b/src/Lamar/Diagnostics/QueryModel.cs
index e52e2914..583c2e0a 100644
--- a/src/Lamar/Diagnostics/QueryModel.cs
+++ b/src/Lamar/Diagnostics/QueryModel.cs
@@ -4,75 +4,72 @@
using JasperFx.Core.Reflection;
using Lamar.IoC;
using Lamar.Scanning.Conventions;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.Diagnostics
-{
- internal class QueryModel : IModel
- {
- private readonly Scope _scope;
-
- public QueryModel(Scope scope)
- {
- _scope = scope;
- }
+namespace Lamar.Diagnostics;
- public IServiceFamilyConfiguration For()
- {
- return For(typeof(T));
- }
+internal class QueryModel : IModel
+{
+ private readonly Scope _scope;
- public IServiceFamilyConfiguration For(Type type)
- {
- return new ServiceFamilyConfiguration(_scope.ServiceGraph.ResolveFamily(type), _scope);
- }
+ public QueryModel(Scope scope)
+ {
+ _scope = scope;
+ }
- public IEnumerable ServiceTypes =>
- _scope.ServiceGraph.Families.Values.Select(x => new ServiceFamilyConfiguration(x, _scope));
-
- public IEnumerable InstancesOf(Type serviceType)
- {
- return For(serviceType).Instances;
- }
+ public IServiceFamilyConfiguration For()
+ {
+ return For(typeof(T));
+ }
- public IEnumerable InstancesOf()
- {
- return InstancesOf(typeof(T));
- }
+ public IServiceFamilyConfiguration For(Type type)
+ {
+ return new ServiceFamilyConfiguration(_scope.ServiceGraph.ResolveFamily(type), _scope);
+ }
- public Type DefaultTypeFor()
- {
- return DefaultTypeFor(typeof(T));
- }
+ public IEnumerable ServiceTypes =>
+ _scope.ServiceGraph.Families.Values.Select(x => new ServiceFamilyConfiguration(x, _scope));
- public Type DefaultTypeFor(Type serviceType)
- {
- return _scope.ServiceGraph.FindDefault(serviceType)?.ImplementationType;
- }
+ public IEnumerable InstancesOf(Type serviceType)
+ {
+ return For(serviceType).Instances;
+ }
- public IEnumerable AllInstances => _scope.ServiceGraph.AllInstances().Select(x => new InstanceRef(x, _scope)).ToArray();
- public T[] GetAllPossible() where T : class
- {
- return AllInstances.ToArray()
- .Where(x => x.ImplementationType.CanBeCastTo(typeof(T)))
- .Select(x => x.Resolve())
- .OfType()
- .ToArray();
- }
+ public IEnumerable InstancesOf()
+ {
+ return InstancesOf(typeof(T));
+ }
- public bool HasRegistrationFor(Type serviceType)
- {
- return _scope.ServiceGraph.FindDefault(serviceType) != null;
- }
+ public Type DefaultTypeFor()
+ {
+ return DefaultTypeFor(typeof(T));
+ }
- public bool HasRegistrationFor()
- {
- return _scope.ServiceGraph.FindDefault(typeof(T)) != null;
- }
+ public Type DefaultTypeFor(Type serviceType)
+ {
+ return _scope.ServiceGraph.FindDefault(serviceType)?.ImplementationType;
+ }
- public IEnumerable Scanners => _scope.ServiceGraph.Scanners;
+ public IEnumerable AllInstances =>
+ _scope.ServiceGraph.AllInstances().Select(x => new InstanceRef(x, _scope)).ToArray();
+ public T[] GetAllPossible() where T : class
+ {
+ return AllInstances.ToArray()
+ .Where(x => x.ImplementationType.CanBeCastTo(typeof(T)))
+ .Select(x => x.Resolve())
+ .OfType()
+ .ToArray();
+ }
+ public bool HasRegistrationFor(Type serviceType)
+ {
+ return _scope.ServiceGraph.FindDefault(serviceType) != null;
+ }
+ public bool HasRegistrationFor()
+ {
+ return _scope.ServiceGraph.FindDefault(typeof(T)) != null;
}
+
+ public IEnumerable Scanners => _scope.ServiceGraph.Scanners;
}
\ No newline at end of file
diff --git a/src/Lamar/IActivationInterceptor.cs b/src/Lamar/IActivationInterceptor.cs
index 23340ec7..c0daa8e5 100644
--- a/src/Lamar/IActivationInterceptor.cs
+++ b/src/Lamar/IActivationInterceptor.cs
@@ -1,14 +1,8 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Lamar.IoC;
-namespace Lamar
+namespace Lamar;
+
+public interface IActivationInterceptor
{
- public interface IActivationInterceptor
- {
- T Intercept(Type serviceType, T instance, IServiceContext scope);
- }
-}
+ T Intercept(Type serviceType, T instance, IServiceContext scope);
+}
\ No newline at end of file
diff --git a/src/Lamar/IContainer.cs b/src/Lamar/IContainer.cs
index 18a60834..0c3d9820 100644
--- a/src/Lamar/IContainer.cs
+++ b/src/Lamar/IContainer.cs
@@ -1,98 +1,93 @@
using System;
-using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar
+namespace Lamar;
+
+public interface INestedContainer : IServiceContext, IAsyncDisposable
{
- public interface INestedContainer : IServiceContext, IAsyncDisposable
- {
- ///
- /// Inject an object into a container at runtime. Used primarily for services like
- /// HttpContext that are passed into a nested container
- ///
- /// Service type to inject.
- /// Service instance to inject.
- /// When true, replaces any previously injected value for the service type.
+ ///
+ /// Inject an object into a container at runtime. Used primarily for services like
+ /// HttpContext that are passed into a nested container
+ ///
+ /// Service type to inject.
+ /// Service instance to inject.
+ /// When true, replaces any previously injected value for the service type.
+ void Inject(Type serviceType, object @object, bool replace);
- void Inject( Type serviceType, object @object, bool replace );
+ ///
+ /// Inject an object into a container at runtime. Used primarily for services like
+ /// HttpContext that are passed into a nested container
+ ///
+ /// Service type to inject.
+ /// Service instance to inject.
+ /// When true, replaces any previously injected value for the service type.
+ void Inject(T @object, bool replace);
- ///
- /// Inject an object into a container at runtime. Used primarily for services like
- /// HttpContext that are passed into a nested container
- ///
- /// Service type to inject.
- /// Service instance to inject.
- /// When true, replaces any previously injected value for the service type.
+ ///
+ /// Inject an object into a container at runtime. Used primarily for services like
+ /// HttpContext that are passed into a nested container
+ ///
+ /// Service type to inject.
+ /// Service instance to inject.
+ /// When true, replaces any previously injected value for the service type.
+ void Inject(T @object);
+}
- void Inject( T @object, bool replace );
+public interface IContainer : IServiceContext
+{
+ ///
+ /// Starts a "Nested" Container for atomic, isolated access.
+ ///
+ /// The created nested container.
+ INestedContainer GetNestedContainer();
- ///
- /// Inject an object into a container at runtime. Used primarily for services like
- /// HttpContext that are passed into a nested container
- ///
- /// Service type to inject.
- /// Service instance to inject.
- /// When true, replaces any previously injected value for the service type.
+ ///
+ /// Use with caution! Does a full environment test of the configuration of this container. Will try to create
+ /// every configured instance and afterward calls any methods marked with
+ /// .
+ ///
+ void AssertConfigurationIsValid(AssertMode mode = AssertMode.Full);
- void Inject( T @object );
- }
-
- public interface IContainer : IServiceContext
- {
- ///
- /// Starts a "Nested" Container for atomic, isolated access.
- ///
- /// The created nested container.
- INestedContainer GetNestedContainer();
+ ///
+ /// Add additional registrations to a running service. USE WITH CAUTION.
+ ///
+ ///
+ void Configure(IServiceCollection services);
- ///
- /// Use with caution! Does a full environment test of the configuration of this container. Will try to create
- /// every configured instance and afterward calls any methods marked with
- /// .
- ///
- void AssertConfigurationIsValid(AssertMode mode = AssertMode.Full);
+ ///
+ /// Add additional registrations to a running service. USE WITH CAUTION.
+ ///
+ ///
+ void Configure(Action configure);
+}
- ///
- /// Add additional registrations to a running service. USE WITH CAUTION.
- ///
- ///
- void Configure(IServiceCollection services);
+public enum AssertMode
+{
+ ///
+ /// Only validate on the known configuration of dependencies without trying to build services
+ ///
+ ConfigOnly,
- ///
- /// Add additional registrations to a running service. USE WITH CAUTION.
- ///
- ///
- void Configure(Action configure);
- }
+ ///
+ /// Validate configuration, try to build all services, and execute any environment tests
+ ///
+ Full
+}
- public enum AssertMode
- {
- ///
- /// Only validate on the known configuration of dependencies without trying to build services
- ///
- ConfigOnly,
-
- ///
- /// Validate configuration, try to build all services, and execute any environment tests
- ///
- Full
- }
-
- public enum DisposalLock
- {
- ///
- /// If a user calls IContainer.Dispose(), ignore the request
- ///
- Ignore,
+public enum DisposalLock
+{
+ ///
+ /// If a user calls IContainer.Dispose(), ignore the request
+ ///
+ Ignore,
- ///
- /// Default "just dispose the container" behavior
- ///
- Unlocked,
+ ///
+ /// Default "just dispose the container" behavior
+ ///
+ Unlocked,
- ///
- /// Throws an InvalidOperationException when Dispose() is called
- ///
- ThrowOnDispose
- }
+ ///
+ /// Throws an InvalidOperationException when Dispose() is called
+ ///
+ ThrowOnDispose
}
\ No newline at end of file
diff --git a/src/Lamar/IDecoratorPolicy.cs b/src/Lamar/IDecoratorPolicy.cs
index 025a253c..b6cfb06c 100644
--- a/src/Lamar/IDecoratorPolicy.cs
+++ b/src/Lamar/IDecoratorPolicy.cs
@@ -2,127 +2,117 @@
using System.Linq;
using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar
+namespace Lamar;
+
+///
+/// Custom policy applied at service registration that optionally
+/// wraps the original Instance with a decorator
+///
+public interface IDecoratorPolicy : ILamarPolicy
+{
+ bool TryWrap(Instance inner, out Instance wrapped);
+}
+
+internal interface IMaybeIntercepted
+{
+ bool TryWrap(out Instance wrapped);
+}
+
+internal class MaybeIntercepted : IDecoratorPolicy
{
- ///
- /// Custom policy applied at service registration that optionally
- /// wraps the original Instance with a decorator
- ///
- public interface IDecoratorPolicy : ILamarPolicy
+ internal static readonly MaybeIntercepted Instance = new();
+
+ public bool TryWrap(Instance inner, out Instance wrapped)
{
- bool TryWrap(Instance inner, out Instance wrapped);
+ if (inner is IMaybeIntercepted i)
+ {
+ return i.TryWrap(out wrapped);
+ }
+
+ wrapped = null;
+ return false;
}
+}
- internal interface IMaybeIntercepted
+[LamarIgnore]
+public class DecoratorPolicy : DecoratorPolicy where TDecorator : TService
+{
+ public DecoratorPolicy() : base(typeof(TService), typeof(TDecorator))
{
- bool TryWrap(out Instance wrapped);
}
+}
- internal class MaybeIntercepted : IDecoratorPolicy
+[LamarIgnore]
+public class DecoratorPolicy : IDecoratorPolicy
+{
+ private readonly Type _decoratorType;
+ private readonly Type _serviceType;
+
+ public DecoratorPolicy(Type serviceType, Type decoratorType)
{
- internal static readonly MaybeIntercepted Instance = new MaybeIntercepted();
-
- public bool TryWrap(Instance inner, out Instance wrapped)
+ if (decoratorType.IsAbstract || decoratorType.IsInterface)
{
- if (inner is IMaybeIntercepted i)
- {
- return i.TryWrap(out wrapped);
- }
-
- wrapped = null;
- return false;
+ throw new InvalidOperationException("The decorating type (the 2nd type argument) must be a concrete type");
}
- }
- [LamarIgnore]
- public class DecoratorPolicy : DecoratorPolicy where TDecorator : TService
- {
- public DecoratorPolicy() : base(typeof(TService), typeof(TDecorator))
+ if (serviceType.IsOpenGeneric())
{
+ if (!decoratorType.IsOpenGeneric() || !GenericsPluginGraph.CanBeCast(serviceType, decoratorType))
+ {
+ throw new InvalidOperationException(
+ $"{decoratorType.FullNameInCode()} cannot be cast to {serviceType.FullNameInCode()}");
+ }
}
- }
- [LamarIgnore]
- public class DecoratorPolicy : IDecoratorPolicy
- {
- private readonly Type _serviceType;
- private readonly Type _decoratorType;
+ _serviceType = serviceType;
+ _decoratorType = decoratorType;
- public DecoratorPolicy(Type serviceType, Type decoratorType)
+ if (!serviceType.IsOpenGeneric())
{
- if (decoratorType.IsAbstract || decoratorType.IsInterface)
+ var hasCtorArg = decoratorType.GetConstructors().SelectMany(x => x.GetParameters())
+ .Any(x => x.ParameterType == serviceType);
+
+ if (!hasCtorArg)
{
- throw new InvalidOperationException("The decorating type (the 2nd type argument) must be a concrete type");
+ throw new InvalidOperationException(
+ $"There must be a constructor argument for the inner {serviceType.FullNameInCode()} argument");
}
+ }
+ }
- if (serviceType.IsOpenGeneric())
+ public bool TryWrap(Instance instance, out Instance wrapped)
+ {
+ if (_serviceType.IsOpenGeneric())
+ {
+ if (instance.ServiceType.Closes(_serviceType))
{
- if (!decoratorType.IsOpenGeneric() || !GenericsPluginGraph.CanBeCast(serviceType, decoratorType))
- {
- throw new InvalidOperationException($"{decoratorType.FullNameInCode()} cannot be cast to {serviceType.FullNameInCode()}");
- }
- }
+ var args = instance.ServiceType.GetGenericArguments();
+ var concreteType = _decoratorType.MakeGenericType(args);
- _serviceType = serviceType;
- _decoratorType = decoratorType;
+ var decorator = new ConstructorInstance(instance.ServiceType, concreteType, instance.Lifetime);
+ decorator.AddInline(instance);
- if (!serviceType.IsOpenGeneric())
- {
- var hasCtorArg = decoratorType.GetConstructors().SelectMany(x => x.GetParameters())
- .Any(x => x.ParameterType == serviceType);
+ wrapped = decorator;
- if (!hasCtorArg)
- {
- throw new InvalidOperationException($"There must be a constructor argument for the inner {serviceType.FullNameInCode()} argument");
- }
+ return true;
}
+
+ wrapped = null;
+ return false;
}
- public bool TryWrap(Instance instance, out Instance wrapped)
+ if (instance.ServiceType == _serviceType)
{
- if (_serviceType.IsOpenGeneric())
- {
- if (instance.ServiceType.Closes(_serviceType))
- {
- var args = instance.ServiceType.GetGenericArguments();
- var concreteType = _decoratorType.MakeGenericType(args);
-
- var decorator = new ConstructorInstance(instance.ServiceType, concreteType, instance.Lifetime);
- decorator.AddInline(instance);
-
- wrapped = decorator;
-
- return true;
- }
- else
- {
- wrapped = null;
- return false;
- }
- }
- else
- {
- if (instance.ServiceType == _serviceType)
- {
- var decorator = new ConstructorInstance(_serviceType, _decoratorType, instance.Lifetime);
- decorator.AddInline(instance);
-
- wrapped = decorator;
-
- return true;
- }
- else
- {
- wrapped = null;
- return false;
- }
- }
-
-
+ var decorator = new ConstructorInstance(_serviceType, _decoratorType, instance.Lifetime);
+ decorator.AddInline(instance);
+ wrapped = decorator;
+
+ return true;
}
+
+ wrapped = null;
+ return false;
}
}
\ No newline at end of file
diff --git a/src/Lamar/IFamilyPolicy.cs b/src/Lamar/IFamilyPolicy.cs
index 2b23ef09..20eb1324 100644
--- a/src/Lamar/IFamilyPolicy.cs
+++ b/src/Lamar/IFamilyPolicy.cs
@@ -1,24 +1,23 @@
using System;
-namespace Lamar
+namespace Lamar;
+
+///
+/// Allows Lamar to fill in missing registrations by unknown service types
+/// at runtime
+///
+[LamarIgnore]
+
+#region sample_IFamilyPolicy
+
+public interface IFamilyPolicy : ILamarPolicy
{
-
///
- /// Allows Lamar to fill in missing registrations by unknown service types
- /// at runtime
+ /// Allows you to create missing registrations for an unknown service type
+ /// at runtime.
+ /// Return null if this policy does not apply to the given type
///
- [LamarIgnore]
- #region sample_IFamilyPolicy
- public interface IFamilyPolicy : ILamarPolicy
- {
- ///
- /// Allows you to create missing registrations for an unknown service type
- /// at runtime.
- /// Return null if this policy does not apply to the given type
- ///
- ServiceFamily Build(Type type, ServiceGraph serviceGraph);
- }
- #endregion
-
+ ServiceFamily Build(Type type, ServiceGraph serviceGraph);
+}
-}
\ No newline at end of file
+#endregion
\ No newline at end of file
diff --git a/src/Lamar/IInstancePolicy.cs b/src/Lamar/IInstancePolicy.cs
index 306d7d55..c37ce3f8 100644
--- a/src/Lamar/IInstancePolicy.cs
+++ b/src/Lamar/IInstancePolicy.cs
@@ -1,42 +1,42 @@
-using System;
-using JasperFx.Core.Reflection;
+using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar
+namespace Lamar;
+
+#region sample_IInstancePolicy
+
+///
+/// Custom policy on Instance construction that is evaluated
+/// as part of creating a "build plan"
+///
+public interface IInstancePolicy : ILamarPolicy
{
- #region sample_IInstancePolicy
///
- /// Custom policy on Instance construction that is evaluated
- /// as part of creating a "build plan"
+ /// Apply any conventional changes to the configuration
+ /// of a single Instance
///
-
- public interface IInstancePolicy : ILamarPolicy
- {
- ///
- /// Apply any conventional changes to the configuration
- /// of a single Instance
- ///
- ///
- void Apply(Instance instance);
- }
- #endregion
+ ///
+ void Apply(Instance instance);
+}
- #region sample_ConfiguredInstancePolicy
- ///
- /// Base class for using policies against IConfiguredInstance registrations
- ///
- public abstract class ConfiguredInstancePolicy : IInstancePolicy
+#endregion
+
+#region sample_ConfiguredInstancePolicy
+
+///
+/// Base class for using policies against IConfiguredInstance registrations
+///
+public abstract class ConfiguredInstancePolicy : IInstancePolicy
+{
+ public void Apply(Instance instance)
{
- public void Apply(Instance instance)
+ if (instance is IConfiguredInstance)
{
- if (instance is IConfiguredInstance)
- {
- apply(instance.As());
- }
+ apply(instance.As());
}
-
- protected abstract void apply(IConfiguredInstance instance);
}
- #endregion
-}
\ No newline at end of file
+
+ protected abstract void apply(IConfiguredInstance instance);
+}
+
+#endregion
\ No newline at end of file
diff --git a/src/Lamar/ILamarPolicy.cs b/src/Lamar/ILamarPolicy.cs
index a0685cd2..621204ed 100644
--- a/src/Lamar/ILamarPolicy.cs
+++ b/src/Lamar/ILamarPolicy.cs
@@ -1,8 +1,9 @@
-namespace Lamar
+namespace Lamar;
+
+///
+/// Marker interface letting Lamar know that this object applies
+/// some kind of policy
+///
+public interface ILamarPolicy
{
- ///
- /// Marker interface letting Lamar know that this object applies
- /// some kind of policy
- ///
- public interface ILamarPolicy{}
}
\ No newline at end of file
diff --git a/src/Lamar/IRegistrationPolicy.cs b/src/Lamar/IRegistrationPolicy.cs
index 999d5804..d5f93ef3 100644
--- a/src/Lamar/IRegistrationPolicy.cs
+++ b/src/Lamar/IRegistrationPolicy.cs
@@ -1,13 +1,10 @@
-using Microsoft.Extensions.DependencyInjection;
+namespace Lamar;
-namespace Lamar
+///
+/// Policy that can impact the entire service collection of registrations
+/// on container constructions
+///
+public interface IRegistrationPolicy : ILamarPolicy
{
- ///
- /// Policy that can impact the entire service collection of registrations
- /// on container constructions
- ///
- public interface IRegistrationPolicy : ILamarPolicy
- {
- void Apply(ServiceRegistry services);
- }
+ void Apply(ServiceRegistry services);
}
\ No newline at end of file
diff --git a/src/Lamar/IServiceContext.cs b/src/Lamar/IServiceContext.cs
index d73e2542..fbf5a858 100644
--- a/src/Lamar/IServiceContext.cs
+++ b/src/Lamar/IServiceContext.cs
@@ -2,158 +2,168 @@
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
-using Lamar.Diagnostics;
using JasperFx.CodeGeneration.Model;
+using Lamar.Diagnostics;
+
+namespace Lamar;
-namespace Lamar
+public interface IServiceContext : IServiceProvider, IDisposable, IAsyncDisposable
{
- public interface IServiceContext : IServiceProvider, IDisposable, IAsyncDisposable
- {
-
- ///
- /// Provides queryable access to the configured serviceType's and Instances of this Container.
- ///
- IModel Model { get; }
-
- ///
- /// Creates or finds the default instance of .
- ///
- /// The type which instance is to be created or found.
- /// The default instance of .
- T GetInstance();
-
- ///
- /// Creates or finds the named instance of .
- ///
- /// The type which instance is to be created or found.
- /// The name of the instance.
- /// The named instance of .
- T GetInstance(string name);
-
- ///
- /// Creates or finds the default instance of .
- ///
- /// The type which instance is to be created or found.
- /// The default instance of .
- object GetInstance(Type serviceType);
-
- ///
- /// Creates or finds the named instance of .
- ///
- /// The type which instance is to be created or found.
- /// The name of the instance.
- /// The named instance of .
- object GetInstance(Type serviceType, string name);
-
- ///
- /// Creates or finds the default instance of . Returns the default value of
- /// if it is not known to the container.
- ///
- /// The type which instance is to be created or found.
- /// The default instance of if resolved; the default value of
- /// otherwise.
- T TryGetInstance();
-
- ///
- /// Creates or finds the named instance of . Returns the default value of
- /// if the named instance is not known to the container.
- ///
- /// The type which instance is to be created or found.
- /// The name of the instance.
- /// The named instance of if resolved; the default value of
- /// otherwise.
- T TryGetInstance(string name);
-
- ///
- /// Creates or finds the default instance of . Returns if
- /// is not known to the container.
- ///
- /// The type which instance is to be created or found.
- /// The default instance of if resolved; otherwise.
- ///
- object TryGetInstance(Type serviceType);
-
- ///
- /// Creates or finds the named instance of . Returns if
- /// the named instance is not known to the container.
- ///
- /// The type which instance is to be created or found.
- /// The name of the instance.
- /// The named instance of if resolved; otherwise.
- ///
- object TryGetInstance(Type serviceType, string name);
-
- ///
- /// Suitable for building concrete types that will be resolved only a few times
- /// to avoid the cost of having to register or build out a pre-compiled "build plan"
- /// internally
- ///
- ///
- ///
- T QuickBuild();
-
- ///
- /// Suitable for building concrete types that will be resolved only a few times
- /// to avoid the cost of having to register or build out a pre-compiled "build plan"
- /// internally
- ///
- object QuickBuild(Type objectType);
-
- ///
- /// Suitable for building concrete types that will be resolved only a few times
- /// to avoid the cost of having to register or build out a pre-compiled "build plan"
- /// internally
- ///
- ///
- ///
- IReadOnlyList QuickBuildAll();
-
- ///
- /// Creates or resolves all registered instances of type .
- ///
- /// The type which instances are to be created or resolved.
- /// All created or resolved instances of type .
- IReadOnlyList GetAllInstances();
-
- ///
- /// Creates or resolves all registered instances of the .
- ///
- /// The type which instances are to be created or resolved.
- /// All created or resolved instances of type .
- IEnumerable GetAllInstances(Type serviceType);
-
- ///
- /// Returns a report detailing the complete configuration of all service families and Instances
- ///
- /// Optional parameter to filter the results down to just this service type.
- /// Optional parameter to filter the results down to only service types from this
- /// .
- /// Optional parameter to filter the results down to only service types from this
- /// namespace.
- /// Optional parameter to filter the results down to any service type whose name contains
- /// this text.
- /// The detailed report of the configuration.
- string WhatDoIHave(Type serviceType = null, Assembly assembly = null, string @namespace = null,
- string typeName = null);
-
- ///
- /// Returns a textual report of all the assembly scanners used to build up this Container
- ///
- ///
- string WhatDidIScan();
-
-
- IServiceVariableSource CreateServiceVariableSource();
-
- ///
- /// Returns a report detailing the "build plan" for all the matching types
- ///
- ///
- ///
- ///
- ///
- ///
- string HowDoIBuild(Type serviceType = null, Assembly assembly = null, string @namespace = null,
- string typeName = null);
- }
+ ///
+ /// Provides queryable access to the configured serviceType's and Instances of this Container.
+ ///
+ IModel Model { get; }
+
+ ///
+ /// Creates or finds the default instance of .
+ ///
+ /// The type which instance is to be created or found.
+ /// The default instance of .
+ T GetInstance();
+
+ ///
+ /// Creates or finds the named instance of .
+ ///
+ /// The type which instance is to be created or found.
+ /// The name of the instance.
+ /// The named instance of .
+ T GetInstance(string name);
+
+ ///
+ /// Creates or finds the default instance of .
+ ///
+ /// The type which instance is to be created or found.
+ /// The default instance of .
+ object GetInstance(Type serviceType);
+
+ ///
+ /// Creates or finds the named instance of .
+ ///
+ /// The type which instance is to be created or found.
+ /// The name of the instance.
+ /// The named instance of .
+ object GetInstance(Type serviceType, string name);
+
+ ///
+ /// Creates or finds the default instance of . Returns the default value of
+ /// if it is not known to the container.
+ ///
+ /// The type which instance is to be created or found.
+ ///
+ /// The default instance of if resolved; the default value of
+ /// otherwise.
+ ///
+ T TryGetInstance();
+
+ ///
+ /// Creates or finds the named instance of . Returns the default value of
+ /// if the named instance is not known to the container.
+ ///
+ /// The type which instance is to be created or found.
+ /// The name of the instance.
+ ///
+ /// The named instance of if resolved; the default value of
+ /// otherwise.
+ ///
+ T TryGetInstance(string name);
+
+ ///
+ /// Creates or finds the default instance of . Returns if
+ /// is not known to the container.
+ ///
+ /// The type which instance is to be created or found.
+ ///
+ /// The default instance of if resolved; otherwise.
+ ///
+ object TryGetInstance(Type serviceType);
+
+ ///
+ /// Creates or finds the named instance of . Returns if
+ /// the named instance is not known to the container.
+ ///
+ /// The type which instance is to be created or found.
+ /// The name of the instance.
+ ///
+ /// The named instance of if resolved; otherwise.
+ ///
+ object TryGetInstance(Type serviceType, string name);
+
+ ///
+ /// Suitable for building concrete types that will be resolved only a few times
+ /// to avoid the cost of having to register or build out a pre-compiled "build plan"
+ /// internally
+ ///
+ ///
+ ///
+ T QuickBuild();
+
+ ///
+ /// Suitable for building concrete types that will be resolved only a few times
+ /// to avoid the cost of having to register or build out a pre-compiled "build plan"
+ /// internally
+ ///
+ object QuickBuild(Type objectType);
+
+ ///
+ /// Suitable for building concrete types that will be resolved only a few times
+ /// to avoid the cost of having to register or build out a pre-compiled "build plan"
+ /// internally
+ ///
+ ///
+ ///
+ IReadOnlyList QuickBuildAll();
+
+ ///
+ /// Creates or resolves all registered instances of type .
+ ///
+ /// The type which instances are to be created or resolved.
+ /// All created or resolved instances of type .
+ IReadOnlyList GetAllInstances();
+
+ ///
+ /// Creates or resolves all registered instances of the .
+ ///
+ /// The type which instances are to be created or resolved.
+ /// All created or resolved instances of type .
+ IEnumerable GetAllInstances(Type serviceType);
+
+ ///
+ /// Returns a report detailing the complete configuration of all service families and Instances
+ ///
+ /// Optional parameter to filter the results down to just this service type.
+ ///
+ /// Optional parameter to filter the results down to only service types from this
+ /// .
+ ///
+ ///
+ /// Optional parameter to filter the results down to only service types from this
+ /// namespace.
+ ///
+ ///
+ /// Optional parameter to filter the results down to any service type whose name contains
+ /// this text.
+ ///
+ /// The detailed report of the configuration.
+ string WhatDoIHave(Type serviceType = null, Assembly assembly = null, string @namespace = null,
+ string typeName = null);
+
+ ///
+ /// Returns a textual report of all the assembly scanners used to build up this Container
+ ///
+ ///
+ string WhatDidIScan();
+
+
+ IServiceVariableSource CreateServiceVariableSource();
+
+ ///
+ /// Returns a report detailing the "build plan" for all the matching types
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ string HowDoIBuild(Type serviceType = null, Assembly assembly = null, string @namespace = null,
+ string typeName = null);
}
\ No newline at end of file
diff --git a/src/Lamar/IServiceFamilyConfiguration.cs b/src/Lamar/IServiceFamilyConfiguration.cs
index 8c39f834..db9b32d8 100644
--- a/src/Lamar/IServiceFamilyConfiguration.cs
+++ b/src/Lamar/IServiceFamilyConfiguration.cs
@@ -3,34 +3,33 @@
using Lamar.Diagnostics;
using Lamar.IoC.Instances;
-namespace Lamar
+namespace Lamar;
+
+public interface IServiceFamilyConfiguration
{
- public interface IServiceFamilyConfiguration
- {
- ///
- /// The service type
- ///
- Type ServiceType { get; }
+ ///
+ /// The service type
+ ///
+ Type ServiceType { get; }
- ///
- /// The "instance" that will be used when Container.GetInstance(ServiceType) is called.
- /// See InstanceRef for more information
- ///
- InstanceRef Default { get; }
+ ///
+ /// The "instance" that will be used when Container.GetInstance(ServiceType) is called.
+ /// See InstanceRef for more information
+ ///
+ InstanceRef Default { get; }
- ///
- /// All of the Instance's registered
- /// for this ServiceType
- ///
- IEnumerable Instances { get; }
+ ///
+ /// All of the Instance's registered
+ /// for this ServiceType
+ ///
+ IEnumerable Instances { get; }
- ///
- /// Simply query to see if there are any implementations registered
- ///
- ///
- bool HasImplementations();
+ ///
+ /// Simply query to see if there are any implementations registered
+ ///
+ ///
+ bool HasImplementations();
- // TODO -- add implementation by name?
- }
+ // TODO -- add implementation by name?
}
\ No newline at end of file
diff --git a/src/Lamar/IgnoreAssemblyAttribute.cs b/src/Lamar/IgnoreAssemblyAttribute.cs
index e3207145..b4a4fdcd 100644
--- a/src/Lamar/IgnoreAssemblyAttribute.cs
+++ b/src/Lamar/IgnoreAssemblyAttribute.cs
@@ -1,10 +1,8 @@
using System;
-namespace Lamar
-{
- [AttributeUsage(AttributeTargets.Assembly)]
- public class IgnoreAssemblyAttribute : Attribute
- {
+namespace Lamar;
- }
-}
+[AttributeUsage(AttributeTargets.Assembly)]
+public class IgnoreAssemblyAttribute : Attribute
+{
+}
\ No newline at end of file
diff --git a/src/Lamar/InstanceNameAttribute.cs b/src/Lamar/InstanceNameAttribute.cs
index 72da7db4..2b87d0d4 100644
--- a/src/Lamar/InstanceNameAttribute.cs
+++ b/src/Lamar/InstanceNameAttribute.cs
@@ -1,23 +1,22 @@
using Lamar.IoC.Instances;
-namespace Lamar
+namespace Lamar;
+
+///
+/// Configures the Lamar instance name for resolving
+/// services by name
+///
+public class InstanceNameAttribute : LamarAttribute
{
- ///
- /// Configures the Lamar instance name for resolving
- /// services by name
- ///
- public class InstanceNameAttribute : LamarAttribute
- {
- private readonly string _name;
+ private readonly string _name;
- public InstanceNameAttribute(string name)
- {
- _name = name;
- }
+ public InstanceNameAttribute(string name)
+ {
+ _name = name;
+ }
- public override void Alter(Instance instance)
- {
- instance.Name = _name;
- }
+ public override void Alter(Instance instance)
+ {
+ instance.Name = _name;
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Activation/ActivatingInstance.cs b/src/Lamar/IoC/Activation/ActivatingInstance.cs
index bc8beb9f..7f7ba955 100644
--- a/src/Lamar/IoC/Activation/ActivatingInstance.cs
+++ b/src/Lamar/IoC/Activation/ActivatingInstance.cs
@@ -3,58 +3,61 @@
using Lamar.IoC.Instances;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.IoC.Activation
+namespace Lamar.IoC.Activation;
+
+internal class ActivatingInstance : LambdaInstance
{
- internal class ActivatingInstance : LambdaInstance
+ private readonly Instance _inner;
+
+ public ActivatingInstance(Action action, Instance inner)
+ : base(inner.ServiceType, buildCreator(action, inner), inner.Lifetime)
{
- private readonly Instance _inner;
+ inner.Lifetime = ServiceLifetime.Transient;
+ _inner = inner;
+ }
- public ActivatingInstance(Action action, Instance inner)
- : base(inner.ServiceType, buildCreator(action, inner), inner.Lifetime)
- {
- inner.Lifetime = ServiceLifetime.Transient;
- _inner = inner;
- }
-
- protected override IEnumerable createPlan(ServiceGraph services)
- {
- _inner.CreatePlan(services);
- foreach (var message in _inner.ErrorMessages)
- {
- ErrorMessages.Add(message);
- }
-
- return base.createPlan(services);
- }
-
-
+ protected override IEnumerable createPlan(ServiceGraph services)
+ {
+ _inner.CreatePlan(services);
+ foreach (var message in _inner.ErrorMessages) ErrorMessages.Add(message);
- internal override string GetBuildPlan(Scope rootScope)
- {
- return $"User defined interception{Environment.NewLine}{base.GetBuildPlan(rootScope)}";
- }
+ return base.createPlan(services);
+ }
+
+
+ internal override string GetBuildPlan(Scope rootScope)
+ {
+ return $"User defined interception{Environment.NewLine}{base.GetBuildPlan(rootScope)}";
+ }
- private static Func buildCreator(Action interceptor, Instance inner)
+ private static Func buildCreator(Action interceptor, Instance inner)
+ {
+ switch (inner.Lifetime)
{
- switch (inner.Lifetime)
- {
- case ServiceLifetime.Singleton:
- return s =>
+ case ServiceLifetime.Singleton:
+ return s =>
+ {
+ var raw = inner.QuickResolve(s);
+ if (raw is TActual a)
{
- var raw = inner.QuickResolve(s);
- if (raw is TActual a) interceptor(s, a);
- return (TService) raw;
- };
-
- default:
-
- return s =>
+ interceptor(s, a);
+ }
+
+ return (TService)raw;
+ };
+
+ default:
+
+ return s =>
+ {
+ var raw = inner.Resolve(s);
+ if (raw is TActual a)
{
- var raw = inner.Resolve(s);
- if (raw is TActual a) interceptor(s, a);
- return (TService) raw;
- };
- }
+ interceptor(s, a);
+ }
+
+ return (TService)raw;
+ };
}
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Activation/ActivationPolicy.cs b/src/Lamar/IoC/Activation/ActivationPolicy.cs
index 06821e74..4b9be57c 100644
--- a/src/Lamar/IoC/Activation/ActivationPolicy.cs
+++ b/src/Lamar/IoC/Activation/ActivationPolicy.cs
@@ -1,44 +1,44 @@
using System;
using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Activation
+namespace Lamar.IoC.Activation;
+
+internal class ActivationPolicy : IDecoratorPolicy
{
- internal class ActivationPolicy : IDecoratorPolicy
+ private readonly Action _action;
+
+ public ActivationPolicy(Action action)
{
- private readonly Action _action;
+ _action = action;
+ }
- public ActivationPolicy(Action action)
+ public bool TryWrap(Instance inner, out Instance wrapped)
+ {
+ if (TestInstance(inner))
{
- _action = action;
- }
+ wrapped = typeof(ActivatingInstance<,>).CloseAndBuildAs(_action, inner, typeof(T),
+ inner.ServiceType);
- public virtual bool TestInstance(Instance inner)
- {
- if (inner.ServiceType == typeof(T))
- {
- return true;
- }
+ return true;
+ }
- if (inner.ImplementationType == null) return false;
+ wrapped = null;
+ return false;
+ }
- return inner.ImplementationType.CanBeCastTo();
+ public virtual bool TestInstance(Instance inner)
+ {
+ if (inner.ServiceType == typeof(T))
+ {
+ return true;
}
- public bool TryWrap(Instance inner, out Instance wrapped)
+ if (inner.ImplementationType == null)
{
- if (TestInstance(inner))
- {
- wrapped = typeof(ActivatingInstance<,>).CloseAndBuildAs(_action, inner, typeof(T),
- inner.ServiceType);
-
- return true;
- }
-
- wrapped = null;
return false;
}
+ return inner.ImplementationType.CanBeCastTo();
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Activation/InterceptingInstance.cs b/src/Lamar/IoC/Activation/InterceptingInstance.cs
index 1d87c336..a02b3b31 100644
--- a/src/Lamar/IoC/Activation/InterceptingInstance.cs
+++ b/src/Lamar/IoC/Activation/InterceptingInstance.cs
@@ -1,74 +1,70 @@
using System;
using System.Collections.Generic;
+using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.IoC.Activation
+namespace Lamar.IoC.Activation;
+
+internal class InterceptingInstance : LambdaInstance
+ where TImplementation : TService
{
- internal class InterceptingInstance : LambdaInstance where TImplementation : TService
+ private readonly Instance _inner;
+
+ public InterceptingInstance(Func interceptor, Instance inner)
+ : base(inner.ServiceType, buildCreator(interceptor, inner), inner.Lifetime)
{
- private readonly Instance _inner;
+ inner.Lifetime = ServiceLifetime.Transient;
+ _inner = inner;
+ }
- public InterceptingInstance(Func interceptor, Instance inner)
-
- : base(inner.ServiceType, buildCreator(interceptor, inner), inner.Lifetime)
- {
- inner.Lifetime = ServiceLifetime.Transient;
- _inner = inner;
- }
+ protected override IEnumerable createPlan(ServiceGraph services)
+ {
+ _inner.CreatePlan(services);
+ foreach (var message in _inner.ErrorMessages) ErrorMessages.Add(message);
- protected override IEnumerable createPlan(ServiceGraph services)
- {
- _inner.CreatePlan(services);
- foreach (var message in _inner.ErrorMessages)
- {
- ErrorMessages.Add(message);
- }
-
- return base.createPlan(services);
- }
-
-
+ return base.createPlan(services);
+ }
- internal override string GetBuildPlan(Scope rootScope)
- {
- return $"User defined interception{Environment.NewLine}{base.GetBuildPlan(rootScope)}";
- }
- private static Func buildCreator(Func interceptor, Instance inner)
+ internal override string GetBuildPlan(Scope rootScope)
+ {
+ return $"User defined interception{Environment.NewLine}{base.GetBuildPlan(rootScope)}";
+ }
+
+ private static Func buildCreator(Func interceptor,
+ Instance inner)
+ {
+ switch (inner.Lifetime)
{
- switch (inner.Lifetime)
- {
- case ServiceLifetime.Singleton:
- return s =>
+ case ServiceLifetime.Singleton:
+ return s =>
+ {
+ var raw = inner.QuickResolve(s);
+ return raw switch
{
- var raw = inner.QuickResolve(s);
- return raw switch
- {
- TImplementation inner => interceptor(s.Root, inner),
- null => throw new InvalidOperationException(
- $"Inner instance {inner} of activator returned null"),
- _ => throw new InvalidCastException(
- $"Activation interceptor expected type {typeof(TImplementation).FullNameInCode()}, but was {raw.GetType().FullNameInCode()}")
- };
+ TImplementation inner => interceptor(s.Root, inner),
+ null => throw new InvalidOperationException(
+ $"Inner instance {inner} of activator returned null"),
+ _ => throw new InvalidCastException(
+ $"Activation interceptor expected type {typeof(TImplementation).FullNameInCode()}, but was {raw.GetType().FullNameInCode()}")
};
-
- default:
+ };
+
+ default:
- return s =>
+ return s =>
+ {
+ var raw = inner.Resolve(s);
+ return raw switch
{
- var raw = inner.Resolve(s);
- return raw switch
- {
- TImplementation inner => interceptor(s, inner),
- null => throw new InvalidOperationException(
- $"Inner instance {inner} of activator returned null"),
- _ => throw new InvalidCastException(
- $"Activation interceptor expected type {typeof(TImplementation).FullNameInCode()}, but was {raw.GetType().FullNameInCode()}")
- };
+ TImplementation inner => interceptor(s, inner),
+ null => throw new InvalidOperationException(
+ $"Inner instance {inner} of activator returned null"),
+ _ => throw new InvalidCastException(
+ $"Activation interceptor expected type {typeof(TImplementation).FullNameInCode()}, but was {raw.GetType().FullNameInCode()}")
};
- }
+ };
}
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Activation/InterceptorPolicy.cs b/src/Lamar/IoC/Activation/InterceptorPolicy.cs
index 5ba3a30c..f636c372 100644
--- a/src/Lamar/IoC/Activation/InterceptorPolicy.cs
+++ b/src/Lamar/IoC/Activation/InterceptorPolicy.cs
@@ -1,34 +1,32 @@
using System;
using Lamar.IoC.Instances;
-namespace Lamar.IoC.Activation
+namespace Lamar.IoC.Activation;
+
+internal class InterceptorPolicy : IDecoratorPolicy
{
- internal class InterceptorPolicy : IDecoratorPolicy
+ private readonly Func _interceptor;
+
+ public InterceptorPolicy(Func interceptor)
{
- private readonly Func _interceptor;
+ _interceptor = interceptor;
+ }
- public InterceptorPolicy(Func interceptor)
+ public bool TryWrap(Instance inner, out Instance wrapped)
+ {
+ if (TestInstance(inner))
{
- _interceptor = interceptor;
- }
+ wrapped = new InterceptingInstance(_interceptor, inner);
- public virtual bool TestInstance(Instance inner)
- {
- return inner.ServiceType == typeof(T);
+ return true;
}
- public bool TryWrap(Instance inner, out Instance wrapped)
- {
- if (TestInstance(inner))
- {
- wrapped = new InterceptingInstance(_interceptor, inner);
-
- return true;
- }
-
- wrapped = null;
- return false;
- }
+ wrapped = null;
+ return false;
+ }
+ public virtual bool TestInstance(Instance inner)
+ {
+ return inner.ServiceType == typeof(T);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/AsyncDisposableWrapper.cs b/src/Lamar/IoC/AsyncDisposableWrapper.cs
index 58183dc6..a86380f1 100644
--- a/src/Lamar/IoC/AsyncDisposableWrapper.cs
+++ b/src/Lamar/IoC/AsyncDisposableWrapper.cs
@@ -1,25 +1,24 @@
using System;
using System.Threading.Tasks;
-namespace Lamar.IoC
+namespace Lamar.IoC;
+
+internal class AsyncDisposableWrapper : IDisposable, IAsyncDisposable
{
- internal class AsyncDisposableWrapper : IDisposable, IAsyncDisposable
- {
- private readonly IAsyncDisposable _inner;
+ private readonly IAsyncDisposable _inner;
- public AsyncDisposableWrapper(IAsyncDisposable inner)
- {
- _inner = inner;
- }
+ public AsyncDisposableWrapper(IAsyncDisposable inner)
+ {
+ _inner = inner;
+ }
- public void Dispose()
- {
- _inner.DisposeAsync().GetAwaiter().GetResult();
- }
+ public ValueTask DisposeAsync()
+ {
+ return _inner.DisposeAsync();
+ }
- public ValueTask DisposeAsync()
- {
- return _inner.DisposeAsync();
- }
+ public void Dispose()
+ {
+ _inner.DisposeAsync().GetAwaiter().GetResult();
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/BuildMode.cs b/src/Lamar/IoC/BuildMode.cs
index 5478fa50..d47ee94a 100644
--- a/src/Lamar/IoC/BuildMode.cs
+++ b/src/Lamar/IoC/BuildMode.cs
@@ -1,21 +1,20 @@
-namespace Lamar.IoC
+namespace Lamar.IoC;
+
+public enum BuildMode
{
- public enum BuildMode
- {
- ///
- /// Build as if it is used within a handler like
- /// a Jasper message handler or http handler
- ///
- Inline,
-
- ///
- /// Build as a dependency of another object
- ///
- Dependency,
-
- ///
- /// Build as a return value inside of a resolver
- ///
- Build
- }
+ ///
+ /// Build as if it is used within a handler like
+ /// a Jasper message handler or http handler
+ ///
+ Inline,
+
+ ///
+ /// Build as a dependency of another object
+ ///
+ Dependency,
+
+ ///
+ /// Build as a return value inside of a resolver
+ ///
+ Build
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/ContainerValidationException.cs b/src/Lamar/IoC/ContainerValidationException.cs
index 3449fd57..125c666d 100644
--- a/src/Lamar/IoC/ContainerValidationException.cs
+++ b/src/Lamar/IoC/ContainerValidationException.cs
@@ -1,24 +1,22 @@
using System;
-namespace Lamar.IoC
+namespace Lamar.IoC;
+
+public class ContainerValidationException : Exception
{
- public class ContainerValidationException : Exception
+ public ContainerValidationException(string message, string whatDoIHave, string whatDidIScan) : base(message)
{
- ///
- /// A textual report of the container configuration at the point the exception was thrown
- ///
- public string WhatDoIHave { get; }
-
- ///
- /// A textual report of the container type scanning at the point the exception was thrown
- ///
- public string WhatDidIScan { get; }
+ WhatDoIHave = whatDoIHave;
+ WhatDidIScan = whatDidIScan;
+ }
- public ContainerValidationException(string message, string whatDoIHave, string whatDidIScan) : base(message)
- {
- WhatDoIHave = whatDoIHave;
- WhatDidIScan = whatDidIScan;
- }
+ ///
+ /// A textual report of the container configuration at the point the exception was thrown
+ ///
+ public string WhatDoIHave { get; }
- }
+ ///
+ /// A textual report of the container type scanning at the point the exception was thrown
+ ///
+ public string WhatDidIScan { get; }
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/CharacterWidth.cs b/src/Lamar/IoC/Diagnostics/CharacterWidth.cs
index e578cb5f..0c39a9c5 100644
--- a/src/Lamar/IoC/Diagnostics/CharacterWidth.cs
+++ b/src/Lamar/IoC/Diagnostics/CharacterWidth.cs
@@ -1,36 +1,30 @@
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+internal class CharacterWidth
{
- internal class CharacterWidth
- {
- private int _width;
+ internal int Width { get; private set; }
- internal int Width
+ internal static CharacterWidth[] For(int count)
+ {
+ var widths = new CharacterWidth[count];
+ for (var i = 0; i < widths.Length; i++)
{
- get { return _width; }
+ widths[i] = new CharacterWidth();
}
- internal static CharacterWidth[] For(int count)
- {
- var widths = new CharacterWidth[count];
- for (var i = 0; i < widths.Length; i++)
- {
- widths[i] = new CharacterWidth();
- }
-
- return widths;
- }
+ return widths;
+ }
- internal void SetWidth(int width)
+ internal void SetWidth(int width)
+ {
+ if (width > Width)
{
- if (width > _width)
- {
- _width = width;
- }
+ Width = width;
}
+ }
- internal void Add(int add)
- {
- _width += add;
- }
+ internal void Add(int add)
+ {
+ Width += add;
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/DividerLine.cs b/src/Lamar/IoC/Diagnostics/DividerLine.cs
index 326c92dd..4a9793b9 100644
--- a/src/Lamar/IoC/Diagnostics/DividerLine.cs
+++ b/src/Lamar/IoC/Diagnostics/DividerLine.cs
@@ -1,31 +1,27 @@
using System.IO;
-namespace Lamar.IoC.Diagnostics
-{
- internal class DividerLine : Line
- {
- private readonly char _character;
+namespace Lamar.IoC.Diagnostics;
- internal DividerLine(char character)
- {
- _character = character;
- }
+internal class DividerLine : Line
+{
+ private readonly char _character;
- #region Line Members
+ internal DividerLine(char character)
+ {
+ _character = character;
+ }
- public void OverwriteCounts(CharacterWidth[] widths)
- {
- // no-op
- }
+ #region Line Members
- public void Write(TextWriter writer, CharacterWidth[] widths)
- {
- foreach (var width in widths)
- {
- writer.Write(string.Empty.PadRight(width.Width, _character));
- }
- }
+ public void OverwriteCounts(CharacterWidth[] widths)
+ {
+ // no-op
+ }
- #endregion
+ public void Write(TextWriter writer, CharacterWidth[] widths)
+ {
+ foreach (var width in widths) writer.Write(string.Empty.PadRight(width.Width, _character));
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/Line.cs b/src/Lamar/IoC/Diagnostics/Line.cs
index 7a080464..8a97cd6b 100644
--- a/src/Lamar/IoC/Diagnostics/Line.cs
+++ b/src/Lamar/IoC/Diagnostics/Line.cs
@@ -1,10 +1,9 @@
using System.IO;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+internal interface Line
{
- internal interface Line
- {
- void OverwriteCounts(CharacterWidth[] widths);
- void Write(TextWriter writer, CharacterWidth[] widths);
- }
+ void OverwriteCounts(CharacterWidth[] widths);
+ void Write(TextWriter writer, CharacterWidth[] widths);
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/ModelQuery.cs b/src/Lamar/IoC/Diagnostics/ModelQuery.cs
index f734cb8e..bd00e35f 100644
--- a/src/Lamar/IoC/Diagnostics/ModelQuery.cs
+++ b/src/Lamar/IoC/Diagnostics/ModelQuery.cs
@@ -5,55 +5,53 @@
using JasperFx.Core;
using JasperFx.Core.Reflection;
using Lamar.Diagnostics;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+public class ModelQuery
{
- public class ModelQuery
- {
- ///
- /// Optionally specify the namespace of service types in the query. This is inclusive.
- ///
- public string Namespace;
-
- ///
- /// Only list out registrations for the specific ServiceType
- ///
- public Type ServiceType;
-
- ///
- /// Only list out registrations for service types from this assembly
- ///
- public Assembly Assembly;
-
-
- public string TypeName;
-
- public IEnumerable Query(IModel model)
- {
- var enumerable = model.ServiceTypes;
+ ///
+ /// Only list out registrations for service types from this assembly
+ ///
+ public Assembly Assembly;
+
+ ///
+ /// Optionally specify the namespace of service types in the query. This is inclusive.
+ ///
+ public string Namespace;
- if (Namespace.IsNotEmpty())
- {
- enumerable = enumerable.Where(x => x.ServiceType.IsInNamespace(Namespace));
- }
+ ///
+ /// Only list out registrations for the specific ServiceType
+ ///
+ public Type ServiceType;
+
+
+ public string TypeName;
+
+ public IEnumerable Query(IModel model)
+ {
+ var enumerable = model.ServiceTypes;
- if (ServiceType != null)
- {
- enumerable = enumerable.Where(x => x.ServiceType == ServiceType);
- }
+ if (Namespace.IsNotEmpty())
+ {
+ enumerable = enumerable.Where(x => x.ServiceType.IsInNamespace(Namespace));
+ }
- if (Assembly != null)
- {
- enumerable = enumerable.Where(x => x.ServiceType.GetTypeInfo().Assembly == Assembly);
- }
+ if (ServiceType != null)
+ {
+ enumerable = enumerable.Where(x => x.ServiceType == ServiceType);
+ }
- if (TypeName.IsNotEmpty())
- {
- enumerable = enumerable.Where(x => x.ServiceType.Name.ToLower().Contains(TypeName.ToLower()));
- }
+ if (Assembly != null)
+ {
+ enumerable = enumerable.Where(x => x.ServiceType.GetTypeInfo().Assembly == Assembly);
+ }
- return enumerable;
+ if (TypeName.IsNotEmpty())
+ {
+ enumerable = enumerable.Where(x => x.ServiceType.Name.ToLower().Contains(TypeName.ToLower()));
}
+
+ return enumerable;
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/TextLine.cs b/src/Lamar/IoC/Diagnostics/TextLine.cs
index de84d0b4..acbd324b 100644
--- a/src/Lamar/IoC/Diagnostics/TextLine.cs
+++ b/src/Lamar/IoC/Diagnostics/TextLine.cs
@@ -1,40 +1,42 @@
using System.IO;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+internal class TextLine : Line
{
- internal class TextLine : Line
- {
- private readonly string[] _contents;
+ private readonly string[] _contents;
- internal TextLine(string[] contents)
+ internal TextLine(string[] contents)
+ {
+ _contents = contents;
+ for (var i = 0; i < contents.Length; i++)
{
- _contents = contents;
- for (var i = 0; i < contents.Length; i++)
+ if (contents[i] == null)
{
- if (contents[i] == null) contents[i] = string.Empty;
+ contents[i] = string.Empty;
}
}
+ }
- #region Line Members
+ #region Line Members
- public void OverwriteCounts(CharacterWidth[] widths)
+ public void OverwriteCounts(CharacterWidth[] widths)
+ {
+ for (var i = 0; i < widths.Length; i++)
{
- for (var i = 0; i < widths.Length; i++)
- {
- var width = widths[i];
- width.SetWidth(_contents[i].Length);
- }
+ var width = widths[i];
+ width.SetWidth(_contents[i].Length);
}
+ }
- public void Write(TextWriter writer, CharacterWidth[] widths)
+ public void Write(TextWriter writer, CharacterWidth[] widths)
+ {
+ for (var i = 0; i < widths.Length; i++)
{
- for (var i = 0; i < widths.Length; i++)
- {
- var width = widths[i];
- writer.Write(_contents[i].PadRight(width.Width));
- }
+ var width = widths[i];
+ writer.Write(_contents[i].PadRight(width.Width));
}
-
- #endregion
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/TextReportWriter.cs b/src/Lamar/IoC/Diagnostics/TextReportWriter.cs
index f6d7e1fa..0b4c459a 100644
--- a/src/Lamar/IoC/Diagnostics/TextReportWriter.cs
+++ b/src/Lamar/IoC/Diagnostics/TextReportWriter.cs
@@ -2,92 +2,88 @@
using System.Diagnostics;
using System.IO;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+public class TextReportWriter
{
- public class TextReportWriter
+ private readonly int _columnCount;
+ private readonly List _lines = new();
+
+ public TextReportWriter(int columnCount)
{
- private readonly int _columnCount;
- private readonly List _lines = new List();
+ _columnCount = columnCount;
+ }
- public TextReportWriter(int columnCount)
- {
- _columnCount = columnCount;
- }
+ public void AddDivider(char character)
+ {
+ _lines.Add(new DividerLine(character));
+ }
- public void AddDivider(char character)
- {
- _lines.Add(new DividerLine(character));
- }
+ public void AddText(params string[] contents)
+ {
+ _lines.Add(new TextLine(contents));
+ }
- public void AddText(params string[] contents)
- {
- _lines.Add(new TextLine(contents));
- }
+ public void AddContent(string contents)
+ {
+ _lines.Add(new PlainLine(contents));
+ }
- public void AddContent(string contents)
- {
- _lines.Add(new PlainLine(contents));
- }
+ public void Write(StringWriter writer)
+ {
+ var widths = CharacterWidth.For(_columnCount);
- public void Write(StringWriter writer)
- {
- var widths = CharacterWidth.For(_columnCount);
-
- foreach (var line in _lines)
- {
- line.OverwriteCounts(widths);
- }
-
- for (var i = 0; i < widths.Length - 1; i++)
- {
- var width = widths[i];
- width.Add(5);
- }
-
- foreach (var line in _lines)
- {
- writer.WriteLine();
- line.Write(writer, widths);
- }
- }
+ foreach (var line in _lines) line.OverwriteCounts(widths);
- public string Write()
+ for (var i = 0; i < widths.Length - 1; i++)
{
- using (var writer = new StringWriter())
- {
- Write(writer);
-
- return writer.ToString();
- }
+ var width = widths[i];
+ width.Add(5);
}
- public void DumpToDebug()
+ foreach (var line in _lines)
{
- Debug.WriteLine(Write());
+ writer.WriteLine();
+ line.Write(writer, widths);
}
}
- internal class PlainLine : Line
+ public string Write()
{
- public PlainLine(string contents)
+ using (var writer = new StringWriter())
{
- Contents = contents;
+ Write(writer);
+
+ return writer.ToString();
}
+ }
- public string Contents { get; set; }
+ public void DumpToDebug()
+ {
+ Debug.WriteLine(Write());
+ }
+}
+
+internal class PlainLine : Line
+{
+ public PlainLine(string contents)
+ {
+ Contents = contents;
+ }
- #region Line Members
+ public string Contents { get; set; }
- public void OverwriteCounts(CharacterWidth[] widths)
- {
- // no-op
- }
+ #region Line Members
- public void Write(TextWriter writer, CharacterWidth[] widths)
- {
- writer.WriteLine(Contents);
- }
+ public void OverwriteCounts(CharacterWidth[] widths)
+ {
+ // no-op
+ }
- #endregion
+ public void Write(TextWriter writer, CharacterWidth[] widths)
+ {
+ writer.WriteLine(Contents);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/WhatDoIHaveWriter.cs b/src/Lamar/IoC/Diagnostics/WhatDoIHaveWriter.cs
index 18ed90b8..09680888 100644
--- a/src/Lamar/IoC/Diagnostics/WhatDoIHaveWriter.cs
+++ b/src/Lamar/IoC/Diagnostics/WhatDoIHaveWriter.cs
@@ -1,158 +1,155 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
using JasperFx.Core;
using JasperFx.Core.Reflection;
using Lamar.Diagnostics;
-using JasperFx.CodeGeneration;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+public enum WhatDoIHaveDisplay
+{
+ Summary,
+ BuildPlan
+}
+
+public class WhatDoIHaveWriter
{
- public enum WhatDoIHaveDisplay
+ private readonly IModel _graph;
+
+ public WhatDoIHaveWriter(IModel graph)
{
- Summary,
- BuildPlan
+ _graph = graph;
}
-
- public class WhatDoIHaveWriter
- {
- private readonly IModel _graph;
- public WhatDoIHaveWriter(IModel graph)
- {
- _graph = graph;
- }
-
- public string GetText(ModelQuery query, string title = null, WhatDoIHaveDisplay display = WhatDoIHaveDisplay.Summary)
+ public string GetText(ModelQuery query, string title = null,
+ WhatDoIHaveDisplay display = WhatDoIHaveDisplay.Summary)
+ {
+ using (var writer = new StringWriter())
{
- using (var writer = new StringWriter())
+ if (title.IsNotEmpty())
{
- if (title.IsNotEmpty())
- {
- writer.WriteLine(title);
- }
+ writer.WriteLine(title);
+ }
- writer.WriteLine("");
+ writer.WriteLine("");
- var model = _graph;
+ var model = _graph;
- var serviceTypes = query.Query(model);
+ var serviceTypes = query.Query(model);
- writeContentsOfServiceTypes(serviceTypes, writer, display);
+ writeContentsOfServiceTypes(serviceTypes, writer, display);
- return writer.ToString();
- }
+ return writer.ToString();
}
+ }
- private void writeContentsOfServiceTypes(IEnumerable serviceTypes,
- StringWriter writer, WhatDoIHaveDisplay display)
+ private void writeContentsOfServiceTypes(IEnumerable serviceTypes,
+ StringWriter writer, WhatDoIHaveDisplay display)
+ {
+ if (display == WhatDoIHaveDisplay.Summary)
{
- if (display == WhatDoIHaveDisplay.Summary)
- {
- writeSummary(serviceTypes, writer);
- }
- else
- {
- writeBuildPlan(serviceTypes, writer);
- }
+ writeSummary(serviceTypes, writer);
+ }
+ else
+ {
+ writeBuildPlan(serviceTypes, writer);
}
+ }
- private static void writeBuildPlan(IEnumerable serviceTypes, StringWriter writer)
+ private static void writeBuildPlan(IEnumerable serviceTypes, StringWriter writer)
+ {
+ foreach (var serviceType in serviceTypes.Where(x => !x.ServiceType.IsOpenGeneric()))
{
- foreach (var serviceType in serviceTypes.Where(x => !x.ServiceType.IsOpenGeneric()))
+ writer.WriteLine("------------------------------------------------------------------------");
+ writer.WriteLine($"Service Type: {serviceType.ServiceType.FullNameInCode()}");
+
+ foreach (var instance in serviceType.Instances)
{
- writer.WriteLine("------------------------------------------------------------------------");
- writer.WriteLine($"Service Type: {serviceType.ServiceType.FullNameInCode()}");
-
- foreach (var instance in serviceType.Instances)
- {
- writer.WriteLine($"Implementation Type: {instance.ImplementationType.FullNameInCode()}");
- writer.WriteLine($"Instance Name: '{instance.Name}'");
- writer.WriteLine();
- writer.WriteLine(instance.DescribeBuildPlan());
- writer.WriteLine();
- }
+ writer.WriteLine($"Implementation Type: {instance.ImplementationType.FullNameInCode()}");
+ writer.WriteLine($"Instance Name: '{instance.Name}'");
+ writer.WriteLine();
+ writer.WriteLine(instance.DescribeBuildPlan());
+ writer.WriteLine();
}
}
+ }
- private void writeSummary(IEnumerable serviceTypes, StringWriter writer)
- {
- var reportWriter = new TextReportWriter(5);
+ private void writeSummary(IEnumerable serviceTypes, StringWriter writer)
+ {
+ var reportWriter = new TextReportWriter(5);
- reportWriter.AddDivider('=');
- reportWriter.AddText("ServiceType", "Namespace", "Lifecycle", "Description", "Name");
+ reportWriter.AddDivider('=');
+ reportWriter.AddText("ServiceType", "Namespace", "Lifecycle", "Description", "Name");
- serviceTypes.Where(x => x.Instances.Any()).OrderBy(x => x.ServiceType.Name)
- .Each(svc => writeServiceType(svc, reportWriter));
+ serviceTypes.Where(x => x.Instances.Any()).OrderBy(x => x.ServiceType.Name)
+ .Each(svc => writeServiceType(svc, reportWriter));
- reportWriter.AddDivider('=');
+ reportWriter.AddDivider('=');
- reportWriter.Write(writer);
- }
+ reportWriter.Write(writer);
+ }
- private void writeServiceType(IServiceFamilyConfiguration serviceType, TextReportWriter reportWriter)
- {
- reportWriter.AddDivider('-');
+ private void writeServiceType(IServiceFamilyConfiguration serviceType, TextReportWriter reportWriter)
+ {
+ reportWriter.AddDivider('-');
- var name = serviceType.ServiceType.ShortNameInCode();
- var ns = serviceType.ServiceType.Namespace;
+ var name = serviceType.ServiceType.ShortNameInCode();
+ var ns = serviceType.ServiceType.Namespace;
- var contents = new[]
- {
- name,
- ns,
- string.Empty,
- string.Empty,
- string.Empty
- };
-
- if (name.Length > 75)
- {
- contents[0] = contents[1] = string.Empty;
- reportWriter.AddContent("ServiceType: " + name);
- reportWriter.AddContent(" Namespace: " + ns);
- }
-
- var instances = serviceType.Instances.ToArray();
- var instanceRegistry = new List(instances.Length);
+ var contents = new[]
+ {
+ name,
+ ns,
+ string.Empty,
+ string.Empty,
+ string.Empty
+ };
+
+ if (name.Length > 75)
+ {
+ contents[0] = contents[1] = string.Empty;
+ reportWriter.AddContent("ServiceType: " + name);
+ reportWriter.AddContent(" Namespace: " + ns);
+ }
- setContents(contents, instances[0], instanceRegistry);
- reportWriter.AddText(contents);
+ var instances = serviceType.Instances.ToArray();
+ var instanceRegistry = new List(instances.Length);
- for (int i = 1; i < serviceType.Instances.Count(); i++)
- {
- writeInstance(instances[i], serviceType, reportWriter, instanceRegistry);
- }
+ setContents(contents, instances[0], instanceRegistry);
+ reportWriter.AddText(contents);
+
+ for (var i = 1; i < serviceType.Instances.Count(); i++)
+ {
+ writeInstance(instances[i], serviceType, reportWriter, instanceRegistry);
}
+ }
- private void writeInstance(InstanceRef instance, IServiceFamilyConfiguration serviceType,
- TextReportWriter reportWriter,
- List instanceRegistry)
+ private void writeInstance(InstanceRef instance, IServiceFamilyConfiguration serviceType,
+ TextReportWriter reportWriter,
+ List instanceRegistry)
+ {
+ if (instanceRegistry.Contains(instance) || instance == null)
{
- if (instanceRegistry.Contains(instance) || instance == null)
- {
- return;
- }
+ return;
+ }
- var contents = new[] {string.Empty, string.Empty, string.Empty, string.Empty, string.Empty};
+ var contents = new[] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
- setContents(contents, instance, instanceRegistry);
+ setContents(contents, instance, instanceRegistry);
- reportWriter.AddText(contents);
- }
+ reportWriter.AddText(contents);
+ }
- private void setContents(string[] contents, InstanceRef instance, List instanceRegistry)
- {
- contents[2] = instance.Lifetime.ToString();
+ private void setContents(string[] contents, InstanceRef instance, List instanceRegistry)
+ {
+ contents[2] = instance.Lifetime.ToString();
- contents[3] = instance.ToString().Elid(75);
+ contents[3] = instance.ToString().Elid(75);
- contents[4] = instance.Name.Elid(25);
+ contents[4] = instance.Name.Elid(25);
- instanceRegistry.Add(instance);
- }
+ instanceRegistry.Add(instance);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Diagnostics/WriterExtensions.cs b/src/Lamar/IoC/Diagnostics/WriterExtensions.cs
index 7e4a6f66..6e8a76de 100644
--- a/src/Lamar/IoC/Diagnostics/WriterExtensions.cs
+++ b/src/Lamar/IoC/Diagnostics/WriterExtensions.cs
@@ -1,17 +1,16 @@
using System.IO;
-namespace Lamar.IoC.Diagnostics
+namespace Lamar.IoC.Diagnostics;
+
+public static class WriterExtensions
{
- public static class WriterExtensions
+ public static void WriteLine(this TextWriter writer, int spaces, string text)
{
- public static void WriteLine(this TextWriter writer, int spaces, string text)
- {
- writer.WriteLine("".PadRight(spaces) + text);
- }
+ writer.WriteLine("".PadRight(spaces) + text);
+ }
- public static string Line(this int length, char character)
- {
- return "".PadRight(length, character);
- }
+ public static string Line(this int length, char character)
+ {
+ return "".PadRight(length, character);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Enumerables/ArrayInstance.cs b/src/Lamar/IoC/Enumerables/ArrayInstance.cs
index 60b0b773..0f7ca3a5 100644
--- a/src/Lamar/IoC/Enumerables/ArrayInstance.cs
+++ b/src/Lamar/IoC/Enumerables/ArrayInstance.cs
@@ -1,87 +1,86 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using JasperFx.CodeGeneration.Frames;
+using JasperFx.CodeGeneration.Model;
using JasperFx.Core.Reflection;
using Lamar.IoC.Frames;
using Lamar.IoC.Instances;
-using Lamar.IoC.Resolvers;
-using JasperFx.CodeGeneration.Frames;
-using JasperFx.CodeGeneration.Model;
using Microsoft.Extensions.DependencyInjection;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Enumerables
+namespace Lamar.IoC.Enumerables;
+
+internal interface IEnumerableInstance
+{
+ Instance[] Elements { get; }
+ Type ServiceType { get; }
+}
+
+///
+/// Instance type to represent .Net arrays
+///
+///
+public class ArrayInstance : GeneratedInstance, IEnumerableInstance
{
- internal interface IEnumerableInstance
+ public ArrayInstance(Type serviceType) : base(serviceType, typeof(T[]), ServiceLifetime.Transient)
{
- Instance[] Elements { get; }
- Type ServiceType { get; }
+ Name = Variable.DefaultArgName();
}
- ///
- /// Instance type to represent .Net arrays
- ///
- ///
- public class ArrayInstance : GeneratedInstance, IEnumerableInstance
+ public IList InlineDependencies { get; } = new List();
+
+ public Instance[] Elements { get; private set; }
+
+ public override Frame CreateBuildFrame()
{
- private readonly IList _inlines = new List();
+ var variables = new ResolverVariables();
+ var elements = Elements.Select(x => variables.Resolve(x, BuildMode.Dependency)).ToArray();
+
+ variables.MakeNamesUnique();
- public ArrayInstance(Type serviceType) : base(serviceType, typeof(T[]), ServiceLifetime.Transient)
+ return new ArrayAssignmentFrame(this, elements)
{
- Name = Variable.DefaultArgName();
- }
+ ReturnCreated = true
+ };
+ }
- public Instance[] Elements { get; private set; }
+ protected override Variable generateVariableForBuilding(ResolverVariables variables, BuildMode mode, bool isRoot)
+ {
+ // This is goofy, but if the current service is the top level root of the resolver
+ // being created here, make the dependencies all be Dependency mode
+ var dependencyMode = isRoot && mode == BuildMode.Build ? BuildMode.Dependency : mode;
- public override Frame CreateBuildFrame()
- {
- var variables = new ResolverVariables();
- var elements = Elements.Select(x => variables.Resolve(x, BuildMode.Dependency)).ToArray();
-
- variables.MakeNamesUnique();
-
- return new ArrayAssignmentFrame(this, elements)
- {
- ReturnCreated = true
- };
- }
+ var elements = Elements.Select(x => variables.Resolve(x, dependencyMode)).ToArray();
- protected override Variable generateVariableForBuilding(ResolverVariables variables, BuildMode mode, bool isRoot)
- {
- // This is goofy, but if the current service is the top level root of the resolver
- // being created here, make the dependencies all be Dependency mode
- var dependencyMode = isRoot && mode == BuildMode.Build ? BuildMode.Dependency : mode;
-
- var elements = Elements.Select(x => variables.Resolve(x, dependencyMode)).ToArray();
-
- return new ArrayAssignmentFrame(this, elements).Variable;
- }
+ return new ArrayAssignmentFrame(this, elements).Variable;
+ }
- protected override IEnumerable createPlan(ServiceGraph services)
+ protected override IEnumerable createPlan(ServiceGraph services)
+ {
+ if (InlineDependencies.Any())
{
- if (_inlines.Any())
- Elements = _inlines.ToArray();
- else
- Elements = services.FindAll(typeof(T));
-
- return Elements;
+ Elements = InlineDependencies.ToArray();
}
-
- public override object QuickResolve(Scope scope)
+ else
{
- return Elements.Select(x => x.QuickResolve(scope).As()).ToArray();
+ Elements = services.FindAll(typeof(T));
}
- ///
- /// Adds an inline dependency
- ///
- ///
- public void AddInline(Instance instance)
- {
- instance.Parent = this;
- _inlines.Add(instance);
- }
+ return Elements;
+ }
+
+ public override object QuickResolve(Scope scope)
+ {
+ return Elements.Select(x => x.QuickResolve(scope).As()).ToArray();
+ }
- public IList InlineDependencies => _inlines;
+ ///
+ /// Adds an inline dependency
+ ///
+ ///
+ public void AddInline(Instance instance)
+ {
+ instance.Parent = this;
+ InlineDependencies.Add(instance);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Enumerables/EnumerablePolicy.cs b/src/Lamar/IoC/Enumerables/EnumerablePolicy.cs
index b93a2f10..5295d5a7 100644
--- a/src/Lamar/IoC/Enumerables/EnumerablePolicy.cs
+++ b/src/Lamar/IoC/Enumerables/EnumerablePolicy.cs
@@ -1,37 +1,36 @@
using System;
-using System.Collections.Generic;
using System.Linq;
using JasperFx.Core.Reflection;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Enumerables
+namespace Lamar.IoC.Enumerables;
+
+#region sample_EnumerablePolicy
+
+internal class EnumerablePolicy : IFamilyPolicy
{
- #region sample_EnumerablePolicy
- internal class EnumerablePolicy : IFamilyPolicy
+ public ServiceFamily Build(Type type, ServiceGraph serviceGraph)
{
- public ServiceFamily Build(Type type, ServiceGraph serviceGraph)
+ if (type.IsArray)
{
- if (type.IsArray)
- {
- var instanceType = typeof(ArrayInstance<>).MakeGenericType(type.GetElementType());
- var instance = Activator.CreateInstance(instanceType, type).As();
- return new ServiceFamily(type, new IDecoratorPolicy[0], instance);
- }
-
- if (type.IsEnumerable())
- {
- var elementType = type.GetGenericArguments().First();
-
- var instanceType = typeof(ListInstance<>).MakeGenericType(elementType);
- var ctor = instanceType.GetConstructors().Single();
- var instance = ctor.Invoke(new object[]{type}).As();
-
- return new ServiceFamily(type, new IDecoratorPolicy[0], instance);
- }
-
- return null;
+ var instanceType = typeof(ArrayInstance<>).MakeGenericType(type.GetElementType());
+ var instance = Activator.CreateInstance(instanceType, type).As();
+ return new ServiceFamily(type, new IDecoratorPolicy[0], instance);
}
+
+ if (type.IsEnumerable())
+ {
+ var elementType = type.GetGenericArguments().First();
+
+ var instanceType = typeof(ListInstance<>).MakeGenericType(elementType);
+ var ctor = instanceType.GetConstructors().Single();
+ var instance = ctor.Invoke(new object[] { type }).As();
+
+ return new ServiceFamily(type, new IDecoratorPolicy[0], instance);
+ }
+
+ return null;
}
- #endregion
-}
\ No newline at end of file
+}
+
+#endregion
\ No newline at end of file
diff --git a/src/Lamar/IoC/Enumerables/ListInstance.cs b/src/Lamar/IoC/Enumerables/ListInstance.cs
index 468847a7..494c723d 100644
--- a/src/Lamar/IoC/Enumerables/ListInstance.cs
+++ b/src/Lamar/IoC/Enumerables/ListInstance.cs
@@ -1,85 +1,84 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using JasperFx.CodeGeneration.Frames;
+using JasperFx.CodeGeneration.Model;
using JasperFx.Core.Reflection;
using Lamar.IoC.Frames;
using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration;
-using JasperFx.CodeGeneration.Frames;
-using JasperFx.CodeGeneration.Model;
using Microsoft.Extensions.DependencyInjection;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Enumerables
+namespace Lamar.IoC.Enumerables;
+
+///
+/// Instance type to support .Net enumerable types that are not arrays
+///
+///
+public class ListInstance : GeneratedInstance, IEnumerableInstance
{
- ///
- /// Instance type to support .Net enumerable types that are not arrays
- ///
- ///
- public class ListInstance : GeneratedInstance, IEnumerableInstance
+ public ListInstance(Type serviceType) : base(serviceType, typeof(List), ServiceLifetime.Transient)
{
- private readonly IList _inlines = new List();
+ Name = Variable.DefaultArgName(typeof(List));
+ }
- public ListInstance(Type serviceType) : base(serviceType, typeof(List), ServiceLifetime.Transient)
- {
- Name = Variable.DefaultArgName(typeof(List));
- }
+ public IList InlineDependencies { get; } = new List();
- public override Frame CreateBuildFrame()
- {
- var variables = new ResolverVariables();
- var elements = Elements.Select(x => variables.Resolve(x, BuildMode.Dependency)).ToArray();
- variables.MakeNamesUnique();
-
- return new ListAssignmentFrame(this, elements)
- {
- ReturnCreated = true
- };
- }
+ public Instance[] Elements { get; private set; }
- public Instance[] Elements { get; private set; }
+ public override Frame CreateBuildFrame()
+ {
+ var variables = new ResolverVariables();
+ var elements = Elements.Select(x => variables.Resolve(x, BuildMode.Dependency)).ToArray();
+ variables.MakeNamesUnique();
- protected override Variable generateVariableForBuilding(ResolverVariables variables, BuildMode mode, bool isRoot)
+ return new ListAssignmentFrame(this, elements)
{
- // This is goofy, but if the current service is the top level root of the resolver
- // being created here, make the dependencies all be Dependency mode
- var dependencyMode = isRoot && mode == BuildMode.Build ? BuildMode.Dependency : mode;
-
- var elements = Elements.Select(x => variables.Resolve(x, dependencyMode)).ToArray();
+ ReturnCreated = true
+ };
+ }
- return new ListAssignmentFrame(this, elements).Variable;
- }
+ protected override Variable generateVariableForBuilding(ResolverVariables variables, BuildMode mode, bool isRoot)
+ {
+ // This is goofy, but if the current service is the top level root of the resolver
+ // being created here, make the dependencies all be Dependency mode
+ var dependencyMode = isRoot && mode == BuildMode.Build ? BuildMode.Dependency : mode;
- protected override IEnumerable createPlan(ServiceGraph services)
- {
- if (_inlines.Any())
- Elements = _inlines.ToArray();
- else
- Elements = services.FindAll(typeof(T));
+ var elements = Elements.Select(x => variables.Resolve(x, dependencyMode)).ToArray();
- return Elements;
- }
+ return new ListAssignmentFrame(this, elements).Variable;
+ }
- public override object QuickResolve(Scope scope)
+ protected override IEnumerable createPlan(ServiceGraph services)
+ {
+ if (InlineDependencies.Any())
{
- return Elements.Select(x => x.QuickResolve(scope).As()).ToList();
+ Elements = InlineDependencies.ToArray();
}
-
- ///
- /// Adds an inline dependency
- ///
- ///
- public void AddInline(Instance instance)
+ else
{
- instance.Parent = this;
- _inlines.Add(instance);
+ Elements = services.FindAll(typeof(T));
}
- public IList InlineDependencies => _inlines;
+ return Elements;
+ }
- public override string ToString()
- {
- return $"List of all {typeof(T).NameInCode()}";
- }
+ public override object QuickResolve(Scope scope)
+ {
+ return Elements.Select(x => x.QuickResolve(scope).As()).ToList();
+ }
+
+ ///
+ /// Adds an inline dependency
+ ///
+ ///
+ public void AddInline(Instance instance)
+ {
+ instance.Parent = this;
+ InlineDependencies.Add(instance);
+ }
+
+ public override string ToString()
+ {
+ return $"List of all {typeof(T).NameInCode()}";
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ArrayAssignmentFrame.cs b/src/Lamar/IoC/Frames/ArrayAssignmentFrame.cs
index 31f47d16..22137ea8 100644
--- a/src/Lamar/IoC/Frames/ArrayAssignmentFrame.cs
+++ b/src/Lamar/IoC/Frames/ArrayAssignmentFrame.cs
@@ -2,72 +2,69 @@
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
-using JasperFx.Core;
-using Lamar.IoC.Enumerables;
-using Lamar.Scanning.Conventions;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Expressions;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
-using JasperFx.CodeGeneration.Util;
+using JasperFx.Core;
+using JasperFx.Core.Reflection;
+using Lamar.IoC.Enumerables;
+
+namespace Lamar.IoC.Frames;
-namespace Lamar.IoC.Frames
+public class ArrayAssignmentFrame : SyncFrame, IResolverFrame
{
- public class ArrayAssignmentFrame : SyncFrame, IResolverFrame
+ public ArrayAssignmentFrame(ArrayInstance instance, Variable[] elements)
{
- public ArrayAssignmentFrame(ArrayInstance instance, Variable[] elements)
- {
- Elements = elements;
- Variable = new ServiceVariable(instance, this);
+ Elements = elements;
+ Variable = new ServiceVariable(instance, this);
- ElementType = typeof(T);
- }
+ ElementType = typeof(T);
+ }
+ public Type ElementType { get; }
- public Type ElementType { get; }
+ public Variable[] Elements { get; }
- public Variable[] Elements { get; }
+ public Variable Variable { get; }
+ public bool ReturnCreated { get; set; }
+
+ public void WriteExpressions(LambdaDefinition definition)
+ {
+ var init = Expression.NewArrayInit(ElementType, Elements.Select(definition.ExpressionFor));
+ var expr = definition.ExpressionFor(Variable);
- public Variable Variable { get; }
- public bool ReturnCreated { get; set; }
+ var assign = Expression.Assign(expr, init);
+ definition.Body.Add(assign);
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ if (Next == null)
{
- var elements = Elements.Select(x => x.Usage).Join(", ");
-
- var arrayType = ElementType.FullNameInCode();
-
- if (ReturnCreated)
- {
- writer.Write($"return new {arrayType}[]{{{elements}}};");
- }
- else
- {
- writer.Write($"var {Variable.Usage} = new {arrayType}[]{{{elements}}};");
- }
-
-
- Next?.GenerateCode(method, writer);
+ definition.Body.Add(expr);
}
+ }
+
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ var elements = Elements.Select(x => x.Usage).Join(", ");
- public override IEnumerable FindVariables(IMethodVariables chain)
+ var arrayType = ElementType.FullNameInCode();
+
+ if (ReturnCreated)
{
- return Elements;
+ writer.Write($"return new {arrayType}[]{{{elements}}};");
}
-
- public void WriteExpressions(LambdaDefinition definition)
+ else
{
- var init = Expression.NewArrayInit(ElementType, Elements.Select(definition.ExpressionFor));
- var expr = definition.ExpressionFor(Variable);
+ writer.Write($"var {Variable.Usage} = new {arrayType}[]{{{elements}}};");
+ }
- var assign = Expression.Assign(expr, init);
- definition.Body.Add(assign);
- if (Next == null)
- {
- definition.Body.Add(expr);
- }
- }
+ Next?.GenerateCode(method, writer);
+ }
+
+ public override IEnumerable FindVariables(IMethodVariables chain)
+ {
+ return Elements;
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ContainerRootField.cs b/src/Lamar/IoC/Frames/ContainerRootField.cs
index b48c2c7b..c17a317a 100644
--- a/src/Lamar/IoC/Frames/ContainerRootField.cs
+++ b/src/Lamar/IoC/Frames/ContainerRootField.cs
@@ -2,30 +2,31 @@
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
+using JasperFx.Core.Reflection;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public class NestedContainerCreation : AsyncFrame
{
- public class NestedContainerCreation : AsyncFrame
+ public NestedContainerCreation()
{
- public NestedContainerCreation()
- {
- Root = new InjectedField(typeof(IContainer), "rootContainer");
- Nested = new Variable(typeof(IContainer), "nestedContainer", this);
- }
+ Root = new InjectedField(typeof(IContainer), "rootContainer");
+ Nested = new Variable(typeof(IContainer), "nestedContainer", this);
+ }
- public Variable Root { get; }
+ public Variable Root { get; }
- public Variable Nested { get; }
+ public Variable Nested { get; }
- public override IEnumerable FindVariables(IMethodVariables chain)
- {
- yield return Root;
- }
+ public override IEnumerable FindVariables(IMethodVariables chain)
+ {
+ yield return Root;
+ }
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
- {
- writer.Write($"await using var {Nested.Usage} = ({typeof(IContainer).FullNameInCode()})_rootContainer.{nameof(IContainer.GetNestedContainer)}();");
- Next?.GenerateCode(method, writer);
- }
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ writer.Write(
+ $"await using var {Nested.Usage} = ({typeof(IContainer).FullNameInCode()})_rootContainer.{nameof(IContainer.GetNestedContainer)}();");
+ Next?.GenerateCode(method, writer);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/GetInstanceFrame.cs b/src/Lamar/IoC/Frames/GetInstanceFrame.cs
index c630f0c6..b6e9bb6d 100644
--- a/src/Lamar/IoC/Frames/GetInstanceFrame.cs
+++ b/src/Lamar/IoC/Frames/GetInstanceFrame.cs
@@ -2,65 +2,66 @@
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
-using JasperFx.Core.Reflection;
-using Lamar.IoC.Instances;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Expressions;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
-using JasperFx.CodeGeneration.Util;
+using JasperFx.Core.Reflection;
+using Lamar.IoC.Instances;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+#region sample_GetInstanceFrame
+
+public class GetInstanceFrame : SyncFrame, IResolverFrame
{
-
- #region sample_GetInstanceFrame
- public class GetInstanceFrame : SyncFrame, IResolverFrame
+ private static readonly MethodInfo _resolveMethod =
+ ReflectionHelper.GetMethod(x => x.Resolve(null));
+
+ private readonly string _name;
+
+
+ private Variable _scope;
+
+ public GetInstanceFrame(Instance instance)
{
- private static readonly MethodInfo _resolveMethod =
- ReflectionHelper.GetMethod(x => x.Resolve(null));
-
-
-
- private Variable _scope;
- private readonly string _name;
-
- public GetInstanceFrame(Instance instance)
- {
- Variable = new ServiceVariable(instance, this, ServiceDeclaration.ServiceType);
-
- _name = instance.Name;
- }
+ Variable = new ServiceVariable(instance, this, ServiceDeclaration.ServiceType);
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
- {
- writer.Write($"var {Variable.Usage} = {_scope.Usage}.{nameof(Scope.GetInstance)}<{Variable.VariableType.FullNameInCode()}>(\"{_name}\");");
- Next?.GenerateCode(method, writer);
- }
+ _name = instance.Name;
+ }
- public override IEnumerable FindVariables(IMethodVariables chain)
- {
- _scope = chain.FindVariable(typeof(Scope));
- yield return _scope;
- }
-
- public ServiceVariable Variable { get; }
-
- public void WriteExpressions(LambdaDefinition definition)
- {
- var scope = definition.Scope();
- var expr = definition.ExpressionFor(Variable);
+ public ServiceVariable Variable { get; }
- var instance = Variable.Instance;
+ public void WriteExpressions(LambdaDefinition definition)
+ {
+ var scope = definition.Scope();
+ var expr = definition.ExpressionFor(Variable);
+
+ var instance = Variable.Instance;
- var @call = Expression.Call(Expression.Constant(instance), _resolveMethod, scope);
- var assign = Expression.Assign(expr, Expression.Convert(@call, Variable.VariableType));
- definition.Body.Add(assign);
+ var call = Expression.Call(Expression.Constant(instance), _resolveMethod, scope);
+ var assign = Expression.Assign(expr, Expression.Convert(call, Variable.VariableType));
+ definition.Body.Add(assign);
- if (Next is null)
- {
- throw new InvalidCastException($"{typeof(GetInstanceFrame).GetFullName()}.{nameof(Next)} must not be null.");
- }
+ if (Next is null)
+ {
+ throw new InvalidCastException(
+ $"{typeof(GetInstanceFrame).GetFullName()}.{nameof(Next)} must not be null.");
}
}
- #endregion
-}
\ No newline at end of file
+
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ writer.Write(
+ $"var {Variable.Usage} = {_scope.Usage}.{nameof(Scope.GetInstance)}<{Variable.VariableType.FullNameInCode()}>(\"{_name}\");");
+ Next?.GenerateCode(method, writer);
+ }
+
+ public override IEnumerable FindVariables(IMethodVariables chain)
+ {
+ _scope = chain.FindVariable(typeof(Scope));
+ yield return _scope;
+ }
+}
+
+#endregion
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/GetInstanceFromNestedContainerFrame.cs b/src/Lamar/IoC/Frames/GetInstanceFromNestedContainerFrame.cs
index 62d4ad80..91f56845 100644
--- a/src/Lamar/IoC/Frames/GetInstanceFromNestedContainerFrame.cs
+++ b/src/Lamar/IoC/Frames/GetInstanceFromNestedContainerFrame.cs
@@ -2,14 +2,33 @@
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
+using JasperFx.Core.Reflection;
namespace Lamar.IoC.Frames;
public class GetInstanceFromNestedContainerFrame : SyncFrame
{
private readonly Variable _nested;
-
-
+
+
+ public GetInstanceFromNestedContainerFrame(Variable nested, Type serviceType)
+ {
+ _nested = nested;
+ uses.Add(_nested);
+
+ Variable = new Variable(serviceType, this);
+ }
+
+ ///
+ ///
+ /// Optional code fragment to write at the beginning of this
+ /// type in code
+ ///
+ public ICodeFragment? Header { get; set; }
+
+ public Variable Variable { get; }
+
+
///
/// Add a single line comment as the header to this type
///
@@ -18,7 +37,7 @@ public void Comment(string text)
{
Header = new OneLineComment(text);
}
-
+
///
/// Add a multi line comment as the header to this type
///
@@ -27,24 +46,6 @@ public void MultiLineComment(string text)
{
Header = new MultiLineComment(text);
}
-
- ///
- ///
- /// Optional code fragment to write at the beginning of this
- /// type in code
- ///
- public ICodeFragment? Header { get; set; }
-
-
- public GetInstanceFromNestedContainerFrame(Variable nested, Type serviceType)
- {
- _nested = nested;
- uses.Add(_nested);
-
- Variable = new Variable(serviceType, this);
- }
-
- public Variable Variable { get; }
public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
{
@@ -53,8 +54,9 @@ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
writer.WriteLine("");
Header.Write(writer);
}
-
- writer.Write($"var {Variable.Usage} = {_nested.Usage}.{nameof(IContainer.GetInstance)}<{Variable.VariableType.FullNameInCode()}>();");
+
+ writer.Write(
+ $"var {Variable.Usage} = {_nested.Usage}.{nameof(IContainer.GetInstance)}<{Variable.VariableType.FullNameInCode()}>();");
Next?.GenerateCode(method, writer);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/GetServiceFrame.cs b/src/Lamar/IoC/Frames/GetServiceFrame.cs
index 3cd70826..7fe540f2 100644
--- a/src/Lamar/IoC/Frames/GetServiceFrame.cs
+++ b/src/Lamar/IoC/Frames/GetServiceFrame.cs
@@ -2,27 +2,28 @@
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
+using JasperFx.Core.Reflection;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public class GetServiceFrame : SyncFrame
{
- public class GetServiceFrame : SyncFrame
- {
- private readonly Variable _provider;
+ private readonly Variable _provider;
- public GetServiceFrame(Variable provider, Type serviceType)
- {
- _provider = provider ?? throw new ArgumentNullException(nameof(provider));
- uses.Add(provider);
+ public GetServiceFrame(Variable provider, Type serviceType)
+ {
+ _provider = provider ?? throw new ArgumentNullException(nameof(provider));
+ uses.Add(provider);
- Variable = new Variable(serviceType, this);
- }
+ Variable = new Variable(serviceType, this);
+ }
- public Variable Variable { get; }
+ public Variable Variable { get; }
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
- {
- writer.Write($"var {Variable.Usage} = ({Variable.VariableType.FullNameInCode()}){_provider.Usage}.{nameof(IServiceProvider.GetService)}(typeof({Variable.VariableType.FullNameInCode()}));");
- Next?.GenerateCode(method, writer);
- }
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ writer.Write(
+ $"var {Variable.Usage} = ({Variable.VariableType.FullNameInCode()}){_provider.Usage}.{nameof(IServiceProvider.GetService)}(typeof({Variable.VariableType.FullNameInCode()}));");
+ Next?.GenerateCode(method, writer);
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/IServiceVariable.cs b/src/Lamar/IoC/Frames/IServiceVariable.cs
index 6d880122..39c5a89e 100644
--- a/src/Lamar/IoC/Frames/IServiceVariable.cs
+++ b/src/Lamar/IoC/Frames/IServiceVariable.cs
@@ -1,9 +1,8 @@
using Lamar.IoC.Instances;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public interface IServiceVariable
{
- public interface IServiceVariable
- {
- Instance Instance { get; }
- }
+ Instance Instance { get; }
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/InjectedServiceField.cs b/src/Lamar/IoC/Frames/InjectedServiceField.cs
index eb0d4ef2..dfa92fd3 100644
--- a/src/Lamar/IoC/Frames/InjectedServiceField.cs
+++ b/src/Lamar/IoC/Frames/InjectedServiceField.cs
@@ -1,60 +1,56 @@
using System;
using System.Linq.Expressions;
-using JasperFx.Core.Reflection;
-using Lamar.IoC.Instances;
-using Lamar.Scanning.Conventions;
-using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Expressions;
using JasperFx.CodeGeneration.Model;
+using JasperFx.Core.Reflection;
+using Lamar.IoC.Instances;
using Microsoft.Extensions.DependencyInjection;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public class InjectedServiceField : InjectedField, IServiceVariable
{
- public class InjectedServiceField : InjectedField, IServiceVariable
- {
- private bool _isOnlyOne;
+ private bool _isOnlyOne;
- public InjectedServiceField(Instance instance) : base(instance.ServiceType,
- instance.DefaultArgName())
- {
- Instance = instance;
- _isOnlyOne = instance.IsOnlyOneOfServiceType;
- }
+ public InjectedServiceField(Instance instance) : base(instance.ServiceType,
+ instance.DefaultArgName())
+ {
+ Instance = instance;
+ _isOnlyOne = instance.IsOnlyOneOfServiceType;
+ }
- public bool IsOnlyOne
+ public bool IsOnlyOne
+ {
+ private get => _isOnlyOne;
+ set
{
- private get => _isOnlyOne;
- set
+ _isOnlyOne = value;
+ if (value)
{
- _isOnlyOne = value;
- if (value)
- {
- var defaultArgName = DefaultArgName(VariableType);
- OverrideName("_" +defaultArgName);
- CtorArg = defaultArgName;
- }
+ var defaultArgName = DefaultArgName(VariableType);
+ OverrideName("_" + defaultArgName);
+ CtorArg = defaultArgName;
}
}
+ }
- public override string CtorArgDeclaration =>
- IsOnlyOne
- ? $"{ArgType.FullNameInCode()} {CtorArg}"
- : $"[Lamar.Named(\"{Instance.Name}\")] {ArgType.FullNameInCode()} {CtorArg}";
+ public override string CtorArgDeclaration =>
+ IsOnlyOne
+ ? $"{ArgType.FullNameInCode()} {CtorArg}"
+ : $"[Lamar.Named(\"{Instance.Name}\")] {ArgType.FullNameInCode()} {CtorArg}";
- public Instance Instance { get; }
+ public Instance Instance { get; }
- public override Expression ToVariableExpression(LambdaDefinition definition)
+ public override Expression ToVariableExpression(LambdaDefinition definition)
+ {
+ if (Instance.Lifetime == ServiceLifetime.Singleton)
{
- if (Instance.Lifetime == ServiceLifetime.Singleton)
- {
- var scope = definition.Context.As();
- var @object = Instance.QuickResolve(scope);
- return Expression.Constant(@object);
- }
-
- // This needs to be inlined singletons
- throw new NotSupportedException();
+ var scope = definition.Context.As();
+ var @object = Instance.QuickResolve(scope);
+ return Expression.Constant(@object);
}
+
+ // This needs to be inlined singletons
+ throw new NotSupportedException();
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ListAssignmentFrame.cs b/src/Lamar/IoC/Frames/ListAssignmentFrame.cs
index e8f8757b..4f6a1ac9 100644
--- a/src/Lamar/IoC/Frames/ListAssignmentFrame.cs
+++ b/src/Lamar/IoC/Frames/ListAssignmentFrame.cs
@@ -2,74 +2,72 @@
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
-using JasperFx.Core;
-using JasperFx.Core.Reflection;
-using Lamar.IoC.Enumerables;
-using Lamar.Scanning.Conventions;
using JasperFx.CodeGeneration;
using JasperFx.CodeGeneration.Expressions;
using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
-using JasperFx.CodeGeneration.Util;
+using JasperFx.Core;
+using JasperFx.Core.Reflection;
+using Lamar.IoC.Enumerables;
+
+namespace Lamar.IoC.Frames;
-namespace Lamar.IoC.Frames
+public class ListAssignmentFrame : Frame, IResolverFrame
{
- public class ListAssignmentFrame : Frame, IResolverFrame
+ public ListAssignmentFrame(ListInstance instance, Variable[] elements) : base(false)
{
- public ListAssignmentFrame(ListInstance instance, Variable[] elements) : base(false)
- {
- ElementType = typeof(T);
- Variable = new ServiceVariable(instance, this);
+ ElementType = typeof(T);
+ Variable = new ServiceVariable(instance, this);
- Elements = elements;
- }
+ Elements = elements;
+ }
+
+ public Type ElementType { get; }
+
+ public Variable[] Elements { get; }
+
+ public Variable Variable { get; }
+ public bool ReturnCreated { get; set; }
- public Type ElementType { get; }
+ public void WriteExpressions(LambdaDefinition definition)
+ {
+ var listType = typeof(List<>).MakeGenericType(typeof(T));
+ var ctor = listType.GetConstructors().Single(x =>
+ x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType.IsEnumerable());
+
+ var initArray = Expression.NewArrayInit(ElementType, Elements.Select(definition.ExpressionFor));
- public Variable[] Elements { get; }
+ var expr = definition.ExpressionFor(Variable);
- public Variable Variable { get; }
- public bool ReturnCreated { get; set; }
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ var assign = Expression.Assign(expr, Expression.New(ctor, initArray));
+ definition.Body.Add(assign);
+
+ if (Next == null)
{
- var declaration = $"{typeof(List<>).Namespace}.List<{ElementType.FullNameInCode()}>";
-
- var elements = Elements.Select(x => x.Usage).Join(", ");
- if (ReturnCreated)
- {
- writer.Write($"return new {declaration}{{{elements}}};");
- }
- else
- {
- writer.Write($"var {Variable.Usage} = new {declaration}{{{elements}}};");
- }
- Next?.GenerateCode(method, writer);
+ definition.Body.Add(expr);
}
+ }
- public override IEnumerable FindVariables(IMethodVariables chain)
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ var declaration = $"{typeof(List<>).Namespace}.List<{ElementType.FullNameInCode()}>";
+
+ var elements = Elements.Select(x => x.Usage).Join(", ");
+ if (ReturnCreated)
{
- return Elements;
+ writer.Write($"return new {declaration}{{{elements}}};");
}
-
- public void WriteExpressions(LambdaDefinition definition)
+ else
{
+ writer.Write($"var {Variable.Usage} = new {declaration}{{{elements}}};");
+ }
- var listType = typeof(List<>).MakeGenericType(typeof(T));
- var ctor = listType.GetConstructors().Single(x => x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType.IsEnumerable());
-
- var initArray = Expression.NewArrayInit(ElementType, Elements.Select(definition.ExpressionFor));
-
- var expr = definition.ExpressionFor(Variable);
-
-
- var assign = Expression.Assign(expr, Expression.New(ctor, initArray));
- definition.Body.Add(assign);
+ Next?.GenerateCode(method, writer);
+ }
- if (Next == null)
- {
- definition.Body.Add(expr);
- }
- }
+ public override IEnumerable FindVariables(IMethodVariables chain)
+ {
+ return Elements;
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ResolverVariables.cs b/src/Lamar/IoC/Frames/ResolverVariables.cs
index b449c85b..d43af92a 100644
--- a/src/Lamar/IoC/Frames/ResolverVariables.cs
+++ b/src/Lamar/IoC/Frames/ResolverVariables.cs
@@ -2,108 +2,100 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
-using JasperFx.Core;
-using Lamar.IoC.Instances;
using JasperFx.CodeGeneration.Model;
+using Lamar.IoC.Instances;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public class ResolverVariables : IEnumerable, IMethodVariables
{
- public class ResolverVariables : IEnumerable, IMethodVariables
+ private readonly List _all = new();
+ private readonly Dictionary _tracking = new();
+
+ public ResolverVariables()
{
- public int VariableSequence { get; set; }
-
- private readonly List _all = new();
- private readonly Dictionary _tracking = new();
+ Method = this;
+ }
- public ResolverVariables()
- {
- Method = this;
- }
+ public ResolverVariables(IMethodVariables method, IList fields)
+ {
+ Method = method;
+ _all.AddRange(fields);
- public ResolverVariables(IMethodVariables method, IList fields)
- {
- Method = method;
- _all.AddRange(fields);
+ foreach (var field in fields) _tracking[field.Instance] = field;
+ }
- foreach (var field in fields)
- {
- _tracking[field.Instance] = field;
- }
- }
+ public int VariableSequence { get; set; }
- public IMethodVariables Method { get; }
+ public IMethodVariables Method { get; }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
- public IEnumerator GetEnumerator()
- {
- return _all.GetEnumerator();
- }
+ public IEnumerator GetEnumerator()
+ {
+ return _all.GetEnumerator();
+ }
- public Variable Resolve(Instance instance, BuildMode mode)
- {
- if (_tracking.TryGetValue(instance, out var variable))
- {
- return variable;
- }
-
- var fromOutside = Method.TryFindVariable(instance.ServiceType, VariableSource.NotServices);
- if (fromOutside != null && !(fromOutside is ServiceStandinVariable))
- {
- _all.Add(fromOutside);
- _tracking[instance] = fromOutside;
-
- return fromOutside;
- }
-
- variable = instance.CreateVariable(mode, this, false);
- _all.Add(variable);
-
- // Don't track it for possible reuse if it's transient
- if (instance.Lifetime == ServiceLifetime.Scoped)
- {
- _tracking[instance] = variable;
- }
+ Variable IMethodVariables.FindVariable(Type type)
+ {
+ return null;
+ }
- return variable;
- }
+ Variable IMethodVariables.FindVariableByName(Type dependency, string name)
+ {
+ return null;
+ }
- public void MakeNamesUnique()
- {
- var duplicateGroups = _all.GroupBy(x => x.Usage).Where(x => x.Count() > 1).ToArray();
- foreach (var @group in duplicateGroups)
- {
- var i = 0;
- foreach (var variable in group)
- {
- variable.OverrideName(variable.Usage + ++i);
- }
- }
- }
+ bool IMethodVariables.TryFindVariableByName(Type dependency, string name, out Variable variable)
+ {
+ variable = default;
+ return false;
+ }
- Variable IMethodVariables.FindVariable(Type type)
+ Variable IMethodVariables.TryFindVariable(Type type, VariableSource source)
+ {
+ return null;
+ }
+
+ public Variable Resolve(Instance instance, BuildMode mode)
+ {
+ if (_tracking.TryGetValue(instance, out var variable))
{
- return null;
+ return variable;
}
- Variable IMethodVariables.FindVariableByName(Type dependency, string name)
+ var fromOutside = Method.TryFindVariable(instance.ServiceType, VariableSource.NotServices);
+ if (fromOutside != null && !(fromOutside is ServiceStandinVariable))
{
- return null;
+ _all.Add(fromOutside);
+ _tracking[instance] = fromOutside;
+
+ return fromOutside;
}
- bool IMethodVariables.TryFindVariableByName(Type dependency, string name, out Variable variable)
+ variable = instance.CreateVariable(mode, this, false);
+ _all.Add(variable);
+
+ // Don't track it for possible reuse if it's transient
+ if (instance.Lifetime == ServiceLifetime.Scoped)
{
- variable = default;
- return false;
+ _tracking[instance] = variable;
}
- Variable IMethodVariables.TryFindVariable(Type type, VariableSource source)
+ return variable;
+ }
+
+ public void MakeNamesUnique()
+ {
+ var duplicateGroups = _all.GroupBy(x => x.Usage).Where(x => x.Count() > 1).ToArray();
+ foreach (var group in duplicateGroups)
{
- return null;
+ var i = 0;
+ foreach (var variable in group) variable.OverrideName(variable.Usage + ++i);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ServiceScopeFactoryCreation.cs b/src/Lamar/IoC/Frames/ServiceScopeFactoryCreation.cs
index 9298daf5..62d4edcf 100644
--- a/src/Lamar/IoC/Frames/ServiceScopeFactoryCreation.cs
+++ b/src/Lamar/IoC/Frames/ServiceScopeFactoryCreation.cs
@@ -4,37 +4,34 @@
using JasperFx.CodeGeneration.Model;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.IoC.Frames
-{
- public class ServiceScopeFactoryCreation : SyncFrame
- {
- private readonly Variable _factory;
- private readonly Variable _scope;
+namespace Lamar.IoC.Frames;
- public ServiceScopeFactoryCreation()
- {
+public class ServiceScopeFactoryCreation : SyncFrame
+{
+ private readonly Variable _factory;
+ private readonly Variable _scope;
- _scope = new Variable(typeof(IServiceScope), this);
- Provider = new Variable(typeof(IServiceProvider), this);
- Wraps = true;
- }
+ public ServiceScopeFactoryCreation()
+ {
+ _scope = new Variable(typeof(IServiceScope), this);
+ Provider = new Variable(typeof(IServiceProvider), this);
+ Wraps = true;
+ }
- public ServiceScopeFactoryCreation(Variable factory) : this()
- {
- _factory = factory;
- uses.Add(factory);
- }
+ public ServiceScopeFactoryCreation(Variable factory) : this()
+ {
+ _factory = factory;
+ uses.Add(factory);
+ }
- public Variable Provider { get; }
+ public Variable Provider { get; }
- public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ public override void GenerateCode(GeneratedMethod method, ISourceWriter writer)
+ {
+ writer.UsingBlock($"var {_scope.Usage} = {_factory.Usage}.{nameof(IServiceScopeFactory.CreateScope)}()", w =>
{
- writer.UsingBlock($"var {_scope.Usage} = {_factory.Usage}.{nameof(IServiceScopeFactory.CreateScope)}()", w =>
- {
- w.Write($"var {Provider.Usage} = {_scope.Usage}.{nameof(IServiceScope.ServiceProvider)};");
- Next?.GenerateCode(method, w);
- });
- }
-
+ w.Write($"var {Provider.Usage} = {_scope.Usage}.{nameof(IServiceScope.ServiceProvider)};");
+ Next?.GenerateCode(method, w);
+ });
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ServiceStandinVariable.cs b/src/Lamar/IoC/Frames/ServiceStandinVariable.cs
index 4972a0e5..ce9ad53c 100644
--- a/src/Lamar/IoC/Frames/ServiceStandinVariable.cs
+++ b/src/Lamar/IoC/Frames/ServiceStandinVariable.cs
@@ -1,42 +1,44 @@
using System;
-using Lamar.IoC.Instances;
using JasperFx.CodeGeneration.Model;
+using Lamar.IoC.Instances;
-namespace Lamar.IoC.Frames
-{
- public class ServiceStandinVariable : Variable
- {
- private Variable _inner;
- public Instance Instance { get; }
+namespace Lamar.IoC.Frames;
- public ServiceStandinVariable(Instance instance) : base(instance.ServiceType)
- {
- Instance = instance;
- }
+public class ServiceStandinVariable : Variable
+{
+ private Variable _inner;
- public void UseInner(Variable variable)
- {
- _inner = variable ?? throw new ArgumentNullException(nameof(variable));
- Dependencies.Add(variable);
- }
+ public ServiceStandinVariable(Instance instance) : base(instance.ServiceType)
+ {
+ Instance = instance;
+ }
- public override void OverrideName(string variableName)
- {
- _inner.OverrideName(variableName);
- }
+ public Instance Instance { get; }
- public override string Usage
+ public override string Usage
+ {
+ get => _inner?.Usage;
+ protected set
{
- get => _inner?.Usage;
- protected set {
{
base.Usage = value;
- }}
+ }
}
+ }
- public override int GetHashCode()
- {
- return _inner == null ? Instance.GetHashCode() : _inner.GetHashCode();
- }
+ public void UseInner(Variable variable)
+ {
+ _inner = variable ?? throw new ArgumentNullException(nameof(variable));
+ Dependencies.Add(variable);
+ }
+
+ public override void OverrideName(string variableName)
+ {
+ _inner.OverrideName(variableName);
+ }
+
+ public override int GetHashCode()
+ {
+ return _inner == null ? Instance.GetHashCode() : _inner.GetHashCode();
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ServiceVariable.cs b/src/Lamar/IoC/Frames/ServiceVariable.cs
index da11eb39..7ee15e76 100644
--- a/src/Lamar/IoC/Frames/ServiceVariable.cs
+++ b/src/Lamar/IoC/Frames/ServiceVariable.cs
@@ -1,24 +1,25 @@
-using System;
-using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration.Frames;
+using JasperFx.CodeGeneration.Frames;
using JasperFx.CodeGeneration.Model;
+using Lamar.IoC.Instances;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public enum ServiceDeclaration
{
- public enum ServiceDeclaration
- {
- ImplementationType,
- ServiceType
- }
-
- public class ServiceVariable : Variable, IServiceVariable
+ ImplementationType,
+ ServiceType
+}
+
+public class ServiceVariable : Variable, IServiceVariable
+{
+ public ServiceVariable(Instance instance, Frame creator,
+ ServiceDeclaration declaration = ServiceDeclaration.ImplementationType)
+ : base(
+ declaration == ServiceDeclaration.ImplementationType ? instance.ImplementationType : instance.ServiceType,
+ instance.Name.Sanitize(), creator)
{
- public ServiceVariable(Instance instance, Frame creator, ServiceDeclaration declaration = ServiceDeclaration.ImplementationType)
- : base(declaration == ServiceDeclaration.ImplementationType ? instance.ImplementationType : instance.ServiceType, instance.Name.Sanitize(), creator)
- {
- Instance = instance;
- }
-
- public Instance Instance { get; }
+ Instance = instance;
}
+
+ public Instance Instance { get; }
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/ServiceVariableSource.cs b/src/Lamar/IoC/Frames/ServiceVariableSource.cs
index 033af761..cebc7c9f 100644
--- a/src/Lamar/IoC/Frames/ServiceVariableSource.cs
+++ b/src/Lamar/IoC/Frames/ServiceVariableSource.cs
@@ -1,153 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using JasperFx.Core;
using JasperFx.CodeGeneration.Model;
+using JasperFx.Core;
using Microsoft.Extensions.DependencyInjection;
-using JasperFx.CodeGeneration.Util;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public class ServiceVariableSource : IServiceVariableSource
{
- public class ServiceVariableSource : IServiceVariableSource
- {
- public const string UsingNestedContainerDirectly = @"Using the nested container service location approach
+ public const string UsingNestedContainerDirectly = @"Using the nested container service location approach
because at least one dependency is directl using the Lamar container
or IServiceProvider";
- private readonly ServiceGraph _services;
- private readonly IList _standins = new List();
+ private readonly IList _fields = new List();
+
+ private readonly ServiceGraph _services;
+ private readonly IList _standins = new List();
+ private Variable _nested = new NestedContainerCreation().Nested;
+ private bool _usesNestedContainerDirectly;
+
+ public ServiceVariableSource(ServiceGraph services)
+ {
+ _services = services;
+ }
- private readonly IList _fields = new List();
- private bool _usesNestedContainerDirectly;
- private Variable _nested = new NestedContainerCreation().Nested;
+ public bool Matches(Type type)
+ {
+ return _services.CouldResolve(type);
+ }
- public ServiceVariableSource(ServiceGraph services)
+ public Variable Create(Type type)
+ {
+ if (type == typeof(IContainer))
{
- _services = services;
+ _usesNestedContainerDirectly = true;
+ return _nested;
}
- public bool Matches(Type type)
+ if (type == typeof(IServiceProvider))
{
- return _services.CouldResolve(type);
+ _usesNestedContainerDirectly = true;
+ return new CastVariable(_nested, typeof(IServiceProvider));
}
- public Variable Create(Type type)
+ var instance = _services.FindDefault(type);
+ if (instance.Lifetime == ServiceLifetime.Singleton)
{
- if (type == typeof(IContainer))
+ var field = _fields.FirstOrDefault(x => x.Instance == instance);
+ if (field == null)
{
- _usesNestedContainerDirectly = true;
- return _nested;
+ field = new InjectedServiceField(instance);
+ _fields.Add(field);
}
- if (type == typeof(IServiceProvider))
- {
- _usesNestedContainerDirectly = true;
- return new CastVariable(_nested, typeof(IServiceProvider));
- }
-
- var instance = _services.FindDefault(type);
- if (instance.Lifetime == ServiceLifetime.Singleton)
- {
- var field = _fields.FirstOrDefault(x => x.Instance == instance);
- if (field == null)
- {
- field = new InjectedServiceField(instance);
- _fields.Add(field);
- }
-
- return field;
- }
-
- var standin = new ServiceStandinVariable(instance);
- _standins.Add(standin);
-
- return standin;
+ return field;
}
- public void ReplaceVariables(IMethodVariables method)
+ var standin = new ServiceStandinVariable(instance);
+ _standins.Add(standin);
+
+ return standin;
+ }
+
+ public void ReplaceVariables(IMethodVariables method)
+ {
+ if (_usesNestedContainerDirectly || _standins.Any(x => x.Instance.RequiresServiceProvider(method)))
{
- if (_usesNestedContainerDirectly || _standins.Any(x => x.Instance.RequiresServiceProvider(method)))
- {
- useServiceProvider(method);
- }
- else
- {
- useInlineConstruction(method);
- }
+ useServiceProvider(method);
}
-
- public void StartNewType()
+ else
{
- StartNewMethod();
- _fields.Clear();
+ useInlineConstruction(method);
}
+ }
+
+ public void StartNewType()
+ {
+ StartNewMethod();
+ _fields.Clear();
+ }
+
+ public void StartNewMethod()
+ {
+ _nested = new NestedContainerCreation().Nested;
+ _standins.Clear();
+ }
- public void StartNewMethod()
+ private void useInlineConstruction(IMethodVariables method)
+ {
+ // THIS NEEDS TO BE SCOPED PER METHOD!!!
+ var variables = new ResolverVariables(method, _fields);
+ foreach (var standin in _standins)
{
- _nested = new NestedContainerCreation().Nested;
- _standins.Clear();
+ var variable = variables.Resolve(standin.Instance, BuildMode.Inline);
+ standin.UseInner(variable);
}
- private void useInlineConstruction(IMethodVariables method)
+ variables.OfType().Each(field =>
{
- // THIS NEEDS TO BE SCOPED PER METHOD!!!
- var variables = new ResolverVariables(method, _fields);
- foreach (var standin in _standins)
- {
- var variable = variables.Resolve(standin.Instance, BuildMode.Inline);
- standin.UseInner(variable);
- }
+ var family = _services.FindAll(field.VariableType);
+ field.IsOnlyOne = family.Length == 1;
+ });
- variables.OfType().Each(field =>
- {
- var family = _services.FindAll(field.VariableType);
- field.IsOnlyOne = family.Length == 1;
- });
-
- variables.MakeNamesUnique();
- }
+ variables.MakeNamesUnique();
+ }
- private void useServiceProvider(IMethodVariables method)
+ private void useServiceProvider(IMethodVariables method)
+ {
+ var written = false;
+ foreach (var standin in _standins)
{
- bool written = false;
- foreach (var standin in _standins)
+ var frame = new GetInstanceFromNestedContainerFrame(_nested, standin.VariableType);
+ var variable = frame.Variable;
+
+ // Write description of why this had to use the nested container
+ if (standin.Instance.RequiresServiceProvider(method))
{
- var frame = new GetInstanceFromNestedContainerFrame(_nested, standin.VariableType);
- var variable = frame.Variable;
-
- // Write description of why this had to use the nested container
- if (standin.Instance.RequiresServiceProvider(method))
- {
- var comment = standin.Instance.WhyRequireServiceProvider(method);
-
- if (_usesNestedContainerDirectly && !written)
- {
- comment += Environment.NewLine;
- comment += UsingNestedContainerDirectly;
-
- written = true;
- }
-
- frame.MultiLineComment(comment);
- }
- else if (_usesNestedContainerDirectly && !written)
+ var comment = standin.Instance.WhyRequireServiceProvider(method);
+
+ if (_usesNestedContainerDirectly && !written)
{
- frame.MultiLineComment(UsingNestedContainerDirectly);
+ comment += Environment.NewLine;
+ comment += UsingNestedContainerDirectly;
+
written = true;
}
-
- standin.UseInner(variable);
- }
- var duplicates = _standins.GroupBy(x => x.Usage).Where(x => x.Count() > 1);
- foreach (var duplicate in duplicates)
+ frame.MultiLineComment(comment);
+ }
+ else if (_usesNestedContainerDirectly && !written)
{
- var usage = 0;
- foreach (var standinVariable in duplicate)
- {
- standinVariable.OverrideName(standinVariable.Usage + (++usage));
- }
+ frame.MultiLineComment(UsingNestedContainerDirectly);
+ written = true;
}
+
+ standin.UseInner(variable);
+ }
+
+ var duplicates = _standins.GroupBy(x => x.Usage).Where(x => x.Count() > 1);
+ foreach (var duplicate in duplicates)
+ {
+ var usage = 0;
+ foreach (var standinVariable in duplicate) standinVariable.OverrideName(standinVariable.Usage + ++usage);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Frames/VariableExtensions.cs b/src/Lamar/IoC/Frames/VariableExtensions.cs
index d003fa75..f5343e62 100644
--- a/src/Lamar/IoC/Frames/VariableExtensions.cs
+++ b/src/Lamar/IoC/Frames/VariableExtensions.cs
@@ -1,13 +1,12 @@
-using Lamar.IoC.Instances;
-using JasperFx.CodeGeneration.Model;
+using JasperFx.CodeGeneration.Model;
+using Lamar.IoC.Instances;
-namespace Lamar.IoC.Frames
+namespace Lamar.IoC.Frames;
+
+public static class VariableExtensions
{
- public static class VariableExtensions
+ public static bool RefersTo(this Variable variable, Instance instance)
{
- public static bool RefersTo(this Variable variable, Instance instance)
- {
- return instance == (variable as IServiceVariable)?.Instance;
- }
+ return instance == (variable as IServiceVariable)?.Instance;
}
}
\ No newline at end of file
diff --git a/src/Lamar/IoC/Instances/ConstructorInstance.cs b/src/Lamar/IoC/Instances/ConstructorInstance.cs
index 70ce5161..76980c80 100644
--- a/src/Lamar/IoC/Instances/ConstructorInstance.cs
+++ b/src/Lamar/IoC/Instances/ConstructorInstance.cs
@@ -3,568 +3,587 @@
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
+using JasperFx.CodeGeneration.Frames;
+using JasperFx.CodeGeneration.Model;
+using JasperFx.CodeGeneration.Util;
using JasperFx.Core;
using JasperFx.Core.Reflection;
using Lamar.IoC.Activation;
using Lamar.IoC.Frames;
using Lamar.IoC.Setters;
using Lamar.Util;
-using JasperFx.CodeGeneration;
-using JasperFx.CodeGeneration.Frames;
-using JasperFx.CodeGeneration.Model;
-using JasperFx.CodeGeneration.Util;
using Microsoft.Extensions.DependencyInjection;
-namespace Lamar.IoC.Instances
+namespace Lamar.IoC.Instances;
+
+///
+/// Models the construction of a service registration that is built by calling the implementation
+/// type's constructor functions
+///
+///
+///
+public class ConstructorInstance : ConstructorInstance, IMaybeIntercepted
+ where TImplementation : TService
{
- ///
- /// Models the construction of a service registration that is built by calling the implementation
- /// type's constructor functions
- ///
- ///
- ///
- public partial class ConstructorInstance : ConstructorInstance, IMaybeIntercepted where TImplementation : TService
+ private Func _interceptor;
+
+ public ConstructorInstance(Type serviceType, ServiceLifetime lifetime) : base(serviceType, typeof(TImplementation),
+ lifetime)
{
- private Func _interceptor;
+ }
- public ConstructorInstance(Type serviceType, ServiceLifetime lifetime) : base(serviceType, typeof(TImplementation), lifetime)
+ bool IMaybeIntercepted.TryWrap(out Instance wrapped)
+ {
+ if (_interceptor != null)
{
+ wrapped = new InterceptingInstance(_interceptor, this);
+ return true;
}
-
- public ConstructorInstance SelectConstructor(Expression> constructor)
- {
- var finder = new ConstructorFinderVisitor(typeof(TImplementation));
- finder.Visit(constructor);
- Constructor = finder.Constructor;
+ wrapped = null;
+ return false;
+ }
- return this;
- }
-
- ///
- /// Intercept the object being created and potentially replace it with a wrapped
- /// version or another object
- ///
- ///
- ///
- public ConstructorInstance OnCreation(Func interceptor)
- {
- return OnCreation((s, x) => interceptor(x));
- }
-
- ///
- /// Intercept the object being created and potentially replace it with a wrapped
- /// version or another object
- ///
- ///
- ///
- public ConstructorInstance OnCreation(Func interceptor)
- {
- _interceptor = interceptor;
- return this;
- }
-
- ///
- /// Perform some action on the object being created at the time the object is created for the first time by Lamar
- ///
- ///
- ///
- public ConstructorInstance OnCreation(Action activator)
- {
- return OnCreation((s, x) =>
- {
- activator(s, x);
- return x;
- });
- }
-
- ///
- /// Perform some action on the object being created at the time the object is created for the first time by Lamar
- ///
- ///
- ///
- public ConstructorInstance OnCreation(Action activator)
- {
- return OnCreation((s, x) =>
- {
- activator(x);
- return x;
- });
- }
+ public ConstructorInstance SelectConstructor(
+ Expression> constructor)
+ {
+ var finder = new ConstructorFinderVisitor(typeof(TImplementation));
+ finder.Visit(constructor);
+
+ Constructor = finder.Constructor;
+
+ return this;
+ }
+
+ ///
+ /// Intercept the object being created and potentially replace it with a wrapped
+ /// version or another object
+ ///
+ ///
+ ///
+ public ConstructorInstance OnCreation(Func