Skip to content

Commit

Permalink
Merge pull request #5 from autofac/develop
Browse files Browse the repository at this point in the history
Merge from head repository
  • Loading branch information
RaymondHuy authored Sep 2, 2019
2 parents bbf44be + d5d376a commit 095331e
Show file tree
Hide file tree
Showing 30 changed files with 182 additions and 132 deletions.
2 changes: 1 addition & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: 4.9.3.{build}
version: 5.0.0.{build}

configuration: Release

Expand Down
3 changes: 2 additions & 1 deletion src/Autofac/Autofac.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

<PropertyGroup>
<Description>Autofac is an IoC container for Microsoft .NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity.</Description>
<VersionPrefix>4.9.3</VersionPrefix>
<VersionPrefix>5.0.0</VersionPrefix>
<TargetFrameworks>netstandard2.0;netstandard1.1;net45</TargetFrameworks>
<LangVersion>latest</LangVersion>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
Expand Down
17 changes: 10 additions & 7 deletions src/Autofac/Builder/StartableManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Globalization;
using System.Globalization;
using System.Linq;
using Autofac.Core;

Expand All @@ -23,23 +22,27 @@ internal static void StartStartableComponents(IComponentContext componentContext
// We track which registrations have already been auto-activated by adding
// a metadata value. If the value is present, we won't re-activate. This helps
// in the container update situation.
foreach (var startable in componentRegistry.RegistrationsFor(new TypedService(typeof(IStartable))).Where(r => !r.Metadata.ContainsKey(MetadataKeys.AutoActivated)))
var startableService = new TypedService(typeof(IStartable));
foreach (var registration in componentRegistry.RegistrationsFor(startableService).Where(r => !r.Metadata.ContainsKey(MetadataKeys.AutoActivated)))
{
try
{
componentContext.ResolveComponent(startable, Enumerable.Empty<Parameter>());
var request = new ResolveRequest(startableService, registration, Enumerable.Empty<Parameter>());
componentContext.ResolveComponent(request);
}
finally
{
startable.Metadata[MetadataKeys.AutoActivated] = true;
registration.Metadata[MetadataKeys.AutoActivated] = true;
}
}

foreach (var registration in componentRegistry.RegistrationsFor(new AutoActivateService()).Where(r => !r.Metadata.ContainsKey(MetadataKeys.AutoActivated)))
var autoActivateService = new AutoActivateService();
foreach (var registration in componentRegistry.RegistrationsFor(autoActivateService).Where(r => !r.Metadata.ContainsKey(MetadataKeys.AutoActivated)))
{
try
{
componentContext.ResolveComponent(registration, Enumerable.Empty<Parameter>());
var request = new ResolveRequest(autoActivateService, registration, Enumerable.Empty<Parameter>());
componentContext.ResolveComponent(request);
}
catch (DependencyResolutionException ex)
{
Expand Down
6 changes: 3 additions & 3 deletions src/Autofac/Core/Activators/Reflection/AutowiringParameter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ public override bool CanSupplyValue(ParameterInfo pi, IComponentContext context,
if (pi == null) throw new ArgumentNullException(nameof(pi));
if (context == null) throw new ArgumentNullException(nameof(context));

IComponentRegistration registration;
if (context.ComponentRegistry.TryGetRegistration(new TypedService(pi.ParameterType), out registration))
var service = new TypedService(pi.ParameterType);
if (context.ComponentRegistry.TryGetRegistration(service, out var registration))
{
valueProvider = () => context.ResolveComponent(registration, Enumerable.Empty<Parameter>());
valueProvider = () => context.ResolveComponent(new ResolveRequest(service, registration, Enumerable.Empty<Parameter>()));
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ private static IEnumerable<PropertyInfo> GetInjectableProperties(Type instanceTy
continue;
}

// SetMethod will be non-null if CanWrite is true.
// Don't want to inject onto static properties.
if (property.SetMethod.IsStatic)
{
continue;
}

var propertyType = property.PropertyType;

if (propertyType.GetTypeInfo().IsValueType && !propertyType.GetTypeInfo().IsEnum)
Expand Down
15 changes: 3 additions & 12 deletions src/Autofac/Core/Container.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,10 @@ public event EventHandler<ResolveOperationBeginningEventArgs> ResolveOperationBe
/// </summary>
public IComponentRegistry ComponentRegistry { get; }

/// <summary>
/// Resolve an instance of the provided registration within the context.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="parameters">Parameters for the instance.</param>
/// <returns>
/// The component instance.
/// </returns>
/// <exception cref="ComponentNotRegisteredException"/>
/// <exception cref="DependencyResolutionException"/>
public object ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters)
/// <inheritdoc />
public object ResolveComponent(ResolveRequest request)
{
return _rootLifetimeScope.ResolveComponent(registration, parameters);
return _rootLifetimeScope.ResolveComponent(request);
}

/// <summary>
Expand Down
19 changes: 4 additions & 15 deletions src/Autofac/Core/Lifetime/LifetimeScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
Expand Down Expand Up @@ -259,27 +258,17 @@ private ScopeRestrictedRegistry CreateScopeRestrictedRegistry(object tag, Action
return locals;
}

/// <summary>
/// Resolve an instance of the provided registration within the context.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="parameters">Parameters for the instance.</param>
/// <returns>
/// The component instance.
/// </returns>
/// <exception cref="Autofac.Core.Registration.ComponentNotRegisteredException"/>
/// <exception cref="DependencyResolutionException"/>
public object ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters)
/// <inheritdoc />
public object ResolveComponent(ResolveRequest request)
{
if (registration == null) throw new ArgumentNullException(nameof(registration));
if (parameters == null) throw new ArgumentNullException(nameof(parameters));
if (request == null) throw new ArgumentNullException(nameof(request));

CheckNotDisposed();

var operation = new ResolveOperation(this);
var handler = ResolveOperationBeginning;
handler?.Invoke(this, new ResolveOperationBeginningEventArgs(operation));
return operation.Execute(registration, parameters);
return operation.Execute(request);
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Core/Registration/ExternalRegistrySource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
// .CreateRegistration()
new ExternalComponentRegistration(
Guid.NewGuid(),
new DelegateActivator(r.Activator.LimitType, (c, p) => c.ResolveComponent(r, p)),
new DelegateActivator(r.Activator.LimitType, (c, p) => c.ResolveComponent(new ResolveRequest(service, r, p))),
new CurrentScopeLifetime(),
InstanceSharing.None,
InstanceOwnership.ExternallyOwned,
Expand Down
8 changes: 3 additions & 5 deletions src/Autofac/Core/Resolving/IResolveOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;

namespace Autofac.Core.Resolving
{
Expand All @@ -35,13 +34,12 @@ namespace Autofac.Core.Resolving
public interface IResolveOperation
{
/// <summary>
/// Get or create and share an instance of <paramref name="registration"/> in the <paramref name="currentOperationScope"/>.
/// Get or create and share an instance of the requested service in the <paramref name="currentOperationScope"/>.
/// </summary>
/// <param name="currentOperationScope">The scope in the hierarchy in which the operation will begin.</param>
/// <param name="registration">The component to resolve.</param>
/// <param name="parameters">Parameters for the component.</param>
/// <param name="request">The resolve request.</param>
/// <returns>The component instance.</returns>
object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable<Parameter> parameters);
object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request);

/// <summary>
/// Raised when the entire operation is complete.
Expand Down
15 changes: 7 additions & 8 deletions src/Autofac/Core/Resolving/InstanceLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@ internal class InstanceLookup : IComponentContext, IInstanceLookup
private const string ActivatorChainExceptionData = "ActivatorChain";

public InstanceLookup(
IComponentRegistration registration,
IResolveOperation context,
ISharingLifetimeScope mostNestedVisibleScope,
IEnumerable<Parameter> parameters)
ResolveRequest request)
{
Parameters = parameters;
ComponentRegistration = registration;
Parameters = request.Parameters;
ComponentRegistration = request.Registration;
_context = context;

try
Expand All @@ -61,13 +60,13 @@ public InstanceLookup(
catch (DependencyResolutionException ex)
{
var services = new StringBuilder();
foreach (var s in registration.Services)
foreach (var s in ComponentRegistration.Services)
{
services.Append("- ");
services.AppendLine(s.Description);
}

var message = string.Format(CultureInfo.CurrentCulture, ComponentActivationResources.UnableToLocateLifetimeScope, registration.Activator.LimitType, services);
var message = string.Format(CultureInfo.CurrentCulture, ComponentActivationResources.UnableToLocateLifetimeScope, ComponentRegistration.Activator.LimitType, services);
throw new DependencyResolutionException(message, ex);
}
}
Expand Down Expand Up @@ -182,9 +181,9 @@ public void Complete()

public IComponentRegistry ComponentRegistry => _activationScope.ComponentRegistry;

public object ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters)
public object ResolveComponent(ResolveRequest request)
{
return _context.GetOrCreateInstance(_activationScope, registration, parameters);
return _context.GetOrCreateInstance(_activationScope, request);
}

public IComponentRegistration ComponentRegistration { get; }
Expand Down
35 changes: 12 additions & 23 deletions src/Autofac/Core/Resolving/ResolveOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Autofac.Core.Registration;

namespace Autofac.Core.Resolving
{
Expand Down Expand Up @@ -54,34 +53,24 @@ public ResolveOperation(ISharingLifetimeScope mostNestedLifetimeScope)
ResetSuccessfulActivations();
}

/// <summary>
/// Resolve an instance of the provided registration within the context.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="parameters">Parameters for the instance.</param>
/// <returns>
/// The component instance.
/// </returns>
/// <exception cref="ComponentNotRegisteredException"/>
/// <exception cref="DependencyResolutionException"/>
public object ResolveComponent(IComponentRegistration registration, IEnumerable<Parameter> parameters)
/// <inheritdoc />
public object ResolveComponent(ResolveRequest request)
{
return GetOrCreateInstance(_mostNestedLifetimeScope, registration, parameters);
return GetOrCreateInstance(_mostNestedLifetimeScope, request);
}

/// <summary>
/// Execute the complete resolve operation.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="parameters">Parameters for the instance.</param>
/// <param name="request">The resolution context.</param>
[SuppressMessage("CA1031", "CA1031", Justification = "General exception gets rethrown in a DependencyResolutionException.")]
public object Execute(IComponentRegistration registration, IEnumerable<Parameter> parameters)
public object Execute(ResolveRequest request)
{
object result;

try
{
result = ResolveComponent(registration, parameters);
result = ResolveComponent(request);
}
catch (ObjectDisposedException)
{
Expand All @@ -103,23 +92,23 @@ public object Execute(IComponentRegistration registration, IEnumerable<Parameter
}

/// <summary>
/// Continue building the object graph by instantiating <paramref name="registration"/> in the
/// Continue building the object graph by instantiating <paramref name="request"/> in the
/// current <paramref name="currentOperationScope"/>.
/// </summary>
/// <param name="currentOperationScope">The current scope of the operation.</param>
/// <param name="registration">The component to activate.</param>
/// <param name="parameters">The parameters for the component.</param>
/// <param name="request">The resolve request.</param>
/// <returns>The resolved instance.</returns>
/// <exception cref="ArgumentNullException"/>
public object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable<Parameter> parameters)
public object GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
{
if (_ended) throw new ObjectDisposedException(ResolveOperationResources.TemporaryContextDisposed, innerException: null);

++_callDepth;

if (_activationStack.Count > 0) CircularDependencyDetector.CheckForCircularDependency(registration, _activationStack, _callDepth);
if (_activationStack.Count > 0)
CircularDependencyDetector.CheckForCircularDependency(request.Registration, _activationStack, _callDepth);

var activation = new InstanceLookup(registration, this, currentOperationScope, parameters);
var activation = new InstanceLookup(this, currentOperationScope, request);

_activationStack.Push(activation);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
(c, p) =>
{
var elements = c.ComponentRegistry.RegistrationsFor(elementTypeService).OrderBy(cr => cr.GetRegistrationOrder());
var items = elements.Select(cr => c.ResolveComponent(cr, p));
var items = elements.Select(cr => c.ResolveComponent(new ResolveRequest(elementTypeService, cr, p)));

return generator(items);
});
Expand Down
2 changes: 1 addition & 1 deletion src/Autofac/Features/Decorators/InstanceDecorator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ internal static object TryDecorateRegistration(
var serviceParameter = new TypedParameter(serviceType, instance);
var contextParameter = new TypedParameter(typeof(IDecoratorContext), decoratorContext);
var invokeParameters = resolveParameters.Concat(new Parameter[] { serviceParameter, contextParameter });
instance = context.ResolveComponent(decorator.Registration, invokeParameters);
instance = context.ResolveComponent(new ResolveRequest(decorator.Service, decorator.Registration, invokeParameters));

decoratorContext = decoratorContext.UpdateContext(instance);
}
Expand Down
24 changes: 15 additions & 9 deletions src/Autofac/Features/GeneratedFactories/FactoryGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public class FactoryGenerator
{
private readonly Func<IComponentContext, IEnumerable<Parameter>, Delegate> _generator;

private static readonly ConstructorInfo RequestConstructor
= ReflectionExtensions.GetConstructor(() => new ResolveRequest(default, default, default));

/// <summary>
/// Initializes a new instance of the <see cref="FactoryGenerator"/> class.
/// </summary>
Expand All @@ -67,7 +70,7 @@ public FactoryGenerator(Type delegateType, Service service, ParameterMapping par

// c.Resolve(...)
return Expression.Call(
ReflectionExtensions.GetMethod<IComponentContext>(cc => cc.ResolveService(default(Service), default(Parameter[]))),
ReflectionExtensions.GetMethod<IComponentContext>(cc => cc.ResolveService(default, default)),
resolveParams);
},
delegateType,
Expand All @@ -77,30 +80,33 @@ public FactoryGenerator(Type delegateType, Service service, ParameterMapping par
/// <summary>
/// Initializes a new instance of the <see cref="FactoryGenerator"/> class.
/// </summary>
/// <param name="service">The service that will be activated in
/// order to create the products of the factory.</param>
/// <param name="productRegistration">The component that will be activated in
/// order to create the products of the factory.</param>
/// <param name="delegateType">The delegate to provide as a factory.</param>
/// <param name="parameterMapping">The parameter mapping mode to use.</param>
public FactoryGenerator(Type delegateType, IComponentRegistration productRegistration, ParameterMapping parameterMapping)
public FactoryGenerator(Type delegateType, Service service, IComponentRegistration productRegistration, ParameterMapping parameterMapping)
{
if (productRegistration == null) throw new ArgumentNullException(nameof(productRegistration));
Enforce.ArgumentTypeIsFunction(delegateType);

_generator = CreateGenerator(
(activatorContextParam, resolveParameterArray) =>
{
// productRegistration, [new Parameter(name, (object)dps)]*
var resolveParams = new Expression[]
{
// new ResolveRequest(service, productRegistration, [new Parameter(name, (object)dps)])*)
var newExpression = Expression.New(
RequestConstructor,
Expression.Constant(service, typeof(Service)),
Expression.Constant(productRegistration, typeof(IComponentRegistration)),
Expression.NewArrayInit(typeof(Parameter), resolveParameterArray),
};
Expression.NewArrayInit(typeof(Parameter), resolveParameterArray));

// c.Resolve(...)
return Expression.Call(
activatorContextParam,
ReflectionExtensions.GetMethod<IComponentContext>(cc => cc.ResolveComponent(default(IComponentRegistration), default(Parameter[]))),
resolveParams);
ReflectionExtensions.GetMethod<IComponentContext>(cc => cc.ResolveComponent(
new ResolveRequest(default, default, default(Parameter[])))),
newExpression);
},
delegateType,
GetParameterMapping(delegateType, parameterMapping));
Expand Down
Loading

0 comments on commit 095331e

Please sign in to comment.