1

I inherited some code in dotnet that I am trying to refactor to use dependency injection. In Spring I have used the @PostConstruct annotation to set up services after Dependency Injection is finished. Is there an equivalent in dotnet?

Spring calls methods annotated with @PostConstruct only once, just after the initialization of the class.

baruchiro
  • 5,088
  • 5
  • 44
  • 66
AltekkeE
  • 43
  • 1
  • 6
  • No, I don't think there is any @PostConstruct annotation in dotnet; there maybe a library out there that emulates that feature though. – PeonProgrammer Jun 24 '19 at 16:27
  • Why do you want to set up services *after* DI? .NET Core DI is primarily constructor-based. An object's constructor can do whatever it likes with the injected services which means it doesn't really need a post-construction step. You only need the `PostConstruct` annotation when you use property-based DI. There is a post-configure facility but that's probably *not* what you want. – Panagiotis Kanavos Jun 24 '19 at 16:28
  • @PeonProgrammer none is needed to begin with. When you have constructor injection, you *know* when DI is done - right before the constructor is called – Panagiotis Kanavos Jun 24 '19 at 16:28

1 Answers1

1

I do not know what @PostConstruct is, but when you perform Dependency Injection in C# (depending on how you implement this), you can just write the code you want inside the constructor.

Assume you have this class:

class MyObj
{
    public MyObj(DependedObj obj1, ILogger logger)
    {
        // Here you can run what you want, with all the depended objects
    }
}

The Dependency Injection will run the constructor, with the objects that need to be defined in the Dependency Injection initialization.

baruchiro
  • 5,088
  • 5
  • 44
  • 66
  • 1
    Partially true, DI mature frameworks often made large use of the autowiring for the properties, so, Constructor is somethiing that happens before all the properties values have been injected – MonDeveloper May 27 '20 at 09:25