Better DI Service Registration with Assembly Scan

dotnet add package Scrutor

Solution 1

We will create three different empty interfaces which mark the implementations for lifetime registration.

Solution 2

We can create attributes just like interfaces and use them similar to the first solution.

Solution 3

So far, we handled the lifetimes separately. Let’s create a common attribute which contains a lifetime value and then decorate services with that attribute.

Run the examples

You can switch the startup settings and run the following controller.


Examples above use FromCallingAssembly at the beginning of each scan, which would register services only in that specific ASP.NET Core Application. If you have separated your services from Application layer into a class library, you might want to use an entry point for that class library. For example, you can create a dummy class ServiceEntryPoint in that library and call FromAssemblyOf<ServiceEntryPoint>() then continue applying the rest of the settings.


In order to make things more easier, I would like to draw your attention to the power of reflection. Let’s say you have services that ends with postfix e.g CountryBusinessService , OrderBusinessService , XBusinessService . You can register them however you want, such as the example below.


Scrutor has an attribute which works similar to the third solution. However, I could not find the documentation about how to use it. Therefore, I will not include it here.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store