Skip to content

Commit

Permalink
Merge pull request #1112 from alistairjevans/develop
Browse files Browse the repository at this point in the history
Fix for #1111 - AutoActivation for Single Instances needs to use a Service
  • Loading branch information
tillig authored Apr 27, 2020
2 parents a6347e8 + ef8f45f commit ff483a2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/Autofac/RegistrationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,14 @@ public static IRegistrationBuilder<T, SimpleActivatorData, SingleRegistrationSty

if (rb.RegistrationData.ActivatedHandlers.Any() || rb.RegistrationData.ActivatingHandlers.Any())
{
var autoStartService = rb.RegistrationData.Services.First();

// https://github.com/autofac/Autofac/issues/1102
// Single instance registrations with activation handlers need to be auto-activated,
// so that other behaviour (such as OnRelease) that expects 'normal' object lifetime behaviour works as expected.
var activationRegistration = new RegistrationBuilder<T, SimpleActivatorData, SingleRegistrationStyle>(
new AutoActivateService(),
new SimpleActivatorData(new DelegateActivator(typeof(T), (c, p) => c.Resolve<T>())),
new SimpleActivatorData(new DelegateActivator(typeof(T), (c, p) => c.ResolveService(autoStartService))),
new SingleRegistrationStyle());

RegistrationBuilder.RegisterSingleComponent(cr, activationRegistration);
Expand Down
27 changes: 26 additions & 1 deletion test/Autofac.Specification.Test/Lifetime/LifetimeEventTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,28 @@ public void OnReleaseForSingletonStillFiresIfNotResolved()
Assert.True(instance.Released);
}

private class ReleasingClass
[Fact]
public void OnReleaseForSingletonAsInterfaceStillFiresIfNotResolved()
{
var builder = new ContainerBuilder();

var instance = new ReleasingClass();

builder.RegisterInstance(instance)
.As<IReleasingService>()
.OnRelease(s => s.Release());

using (var container = builder.Build())
{
using (var scope = container.BeginLifetimeScope())
{
}
}

Assert.True(instance.Released);
}

private class ReleasingClass : IReleasingService
{
public bool Released { get; set; }

Expand All @@ -183,6 +204,10 @@ public void Release()
}
}

private interface IReleasingService
{
}

private class MethodInjection
{
public int Param { get; private set; }
Expand Down

0 comments on commit ff483a2

Please sign in to comment.