Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Capture prop injection instance when the middleware runs #1205

Merged
merged 1 commit into from Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -584,11 +584,13 @@ public RegistrationBuilder(Service defaultService, TActivatorData activatorData,

if (allowCircularDependencies)
{
var capturedInstance = ctxt.Instance;

// If we are allowing circular deps, then we need to run when all requests have completed (similar to Activated).
ctxt.RequestCompleting += (o, args) =>
{
var evCtxt = args.RequestContext;
AutowiringPropertyInjector.InjectProperties(evCtxt, evCtxt.Instance!, propertySelector, evCtxt.Parameters);
AutowiringPropertyInjector.InjectProperties(evCtxt, capturedInstance!, propertySelector, evCtxt.Parameters);
};
}
else
Expand Down
49 changes: 49 additions & 0 deletions test/Autofac.Specification.Test/Features/PropertyInjectionTests.cs
Expand Up @@ -373,6 +373,22 @@ public void SetterInjectionPrivateGet()
Assert.False(instance.GetterCalled);
}

[Fact]
public void DecoratedInstanceWithPropertyInjectionAllowingCircularReferencesStillInjects()
{
var val = "Value";

var builder = new ContainerBuilder();
builder.RegisterInstance(val);
builder.RegisterType<DecoratedService>().As<IMyService>().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
builder.RegisterDecorator<ServiceDecorator, IMyService>();

var container = builder.Build();
var instance = container.Resolve<IMyService>();

instance.AssertProp();
}

private class ConstructorParamNotAttachedToProperty
{
[SuppressMessage("SA1401", "SA1401")]
Expand Down Expand Up @@ -411,5 +427,38 @@ private get
}
}
}

private interface IMyService
{
void AssertProp();
}

private sealed class DecoratedService : IMyService
{
public string Prop { get; set; }

public void AssertProp()
{
if (Prop is null)
{
throw new NullReferenceException();
}
}
}

private sealed class ServiceDecorator : IMyService
{
private readonly IMyService _decorating;

public ServiceDecorator(IMyService decorating)
{
_decorating = decorating;
}

public void AssertProp()
{
_decorating.AssertProp();
}
}
}
}