autofac / autofac/Autofac

Adding decorator moves OnActivated event invocation

Open
#1,361 11 comments 1 reaction 0 assignees View on GitHub
bug
Dominant language
C#
Stars
4.7k
Forks
847
Avg merge
1d 12m
Merged PRs (30d)
2

Description

Given the following service/container setup:

```cs
public class OuterService
{
public OuterService(IMiddleService middle) => Console.WriteLine("Outer");
}

public interface IMiddleService {}

public class MiddleService : IMiddleService
{
public MiddleService(InnerService inner) => Console.WriteLine("Middle");
}

public class InnerService
{
public InnerService() => Console.WriteLine("Inner");
}

builder.RegisterType().SingleInstance();
builder.RegisterType().SingleInstance().As();
builder
.RegisterType()
.SingleInstance()
.OnActivated(_ => Console.WriteLine("Inner activated"))
;
```

I observe the following output on resolving `OuterService`:

```
Inner
Middle
Outer
Inner activated
```

Note that activation event fires _last_ (which allows us, for example, resolve circular dependency, were `Inner` to depend on `Outer`).

Now we add a decorator (everything else stays the same):

```cs
public class Decorator : IMiddleService
{
public Decorator(IMiddleService inner) => Console.WriteLine("Decorator");
}

builder.RegisterDecorator();
```

The output is:

```
Inner
Middle
Decorator
Inner activated
Outer
```

Now the activation event fires after _decorator_, not the last in the pipeline (which in our case brings back circular dependency).

Observed on Autofac 6.2 and 6.5.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the issue with RegisterType, OnActivated, and RegisterDecorator using the setup in the report. Trace the activation and decorator pipeline to compare both registration paths. Done means the OnActivated callback runs after the complete decorated service pipeline, including the decorator, without changing the non-decorated behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.