Question: I'm looking for some way to enforce the checking (runtime, of course) of the proper lifetime registration of dependency-injection services, in .Net Core or higher.

Let's say I have a stateful service like this one:

```
public class MyStatefulService
{
    private object _state;
}

```

However, by mistake, I could register it with the wrong lifetime:

```
services.AddTransient<MyStatefulService>();

```

So, I won't be alerted, but the actual behavior is not what I'd expect: the service is created at every request, and the state won't be preserved.

I wonder if there is a way to reinforce this pattern. For instance, it would be nice if I could decorate the class with an attribute like this:

```
[Singleton]
public class MyStatefulService
{
    private object _state;
}

```

at this point, possibily at startup or at the very first request, the framework should throw if the registration is different than `AddSingleton` (along its overloads).

Similarly, the subject could apply for transient-only services, which shouldn't registered as singletons.

The only solution came in my mind is rather naive, and I don't like so much:

```
//line of principle code
public static class MySingletonChecker
{
    private static HashSet<Type> _set = new HashSet<Type>();

    public static void Validate(Type type)
    {
        if (_set.Contains(type))
        {
            throw new Exception();
        }
        else
        {
            _set.Add(type);
        }
    }
}

public class MyStatefulService
{
    public MyStatefulService()
    {
        MySingletonChecker.Validate(this.GetType());
    }

    private object _state;
}

```

Is there any better solution, hack or anything that helps to prevent errors?

Answer: 
If you want to idiot-proof your code, you can provide an extension method to `IServiceCollection` that registers your service exactly the way it should be.

```
public static void AddMyStatefulService(this IServiceCollection services) 
{
    services.AddSingleton<MyStatefulService>();
}

```

Then in your services configuration section, the developer would type:

```
services.AddMyStatefulService();

```
Another way to validate lifetimes, is by inspecting the entire DI container in the `ConfigureServices` clause.

Each member of a `IServiceCollection` has a `LifeTime` property which gives you the information you're looking for: <https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicedescriptor.lifetime?view=dotnet-plat-ext-5.0#Microsoft_Extensions_DependencyInjection_ServiceDescriptor_Lifetime>