Quicktip: How to run code from DI at startup

I had recently a strange bug in production code. There was no simple way to debug this solution. I needed to test some of the code using production data.

Class to test was using parsing big blob file. I have possibility to get this file in secure way, to test parsing.

The problem was I could not run the whole application and just need to run one service from DI at startup and test code.

The solution was quite simple, and I think it is worth to share. Notice: project is using Autofac and the solution is valid only for this IoC library.

There is an interface IStartable which provide possibility to run service implementing this interface at start of application. While implement, you need to add Start method as above:

public void Start()
{
    Console.WriteLine("This is my fancy service, started at start of application");

    _someDependencyService.SomeFancyMethodToTest();
}

After that, you need to add some code to registration of type inside startup method:

builder.RegisterType<SomeFancyService>().As<IStartable>();