Service layer method inject using Autofac in a .NET Console Application

in this article, I’m going to show how to inject the entity framework’s backend service layer method using Autofac in a .NET console application.

Kelum
2 min readJan 10, 2021

Below diagram showing this application structure overview.

Overall Design

This is the dataset using for the demonstrations.

database sample table values

Class diagram for a sample table

class diagram for the sample table

Sample Table Class File

SampleTable.cs

here I’m going to use a service class file that is extending its interface, service files connection diagram.

SampleService

Sample Service Interface

ISampleService.cs

Sample Service Implementation

SampleService.cs

in order to work with the entity framework, we would have DBContext.
so IContext file is like the following.

IContext.cs

TestDBContext will be generated like the following, once follow the above DB structure I mentioned.

TestDBContext.cs
TestDBContext

from here on, we focus on the path to inject the service layer method.

So we can place the following ServiceModule class file in Console Application end.

ServiceModule.cs

we can build up EFModule class which is extending Module class

EFModule.cs

as usual, in inject class, we can invoke the service method as following

SampleInitialize.cs

then in our Program class Main method we can refer to the above initialize class as following.

Program.cs

Now everything is set up, Once run the project we should be able to see the following output in a console app.

Console App result

Please note that this approach works Entity Framework Version 6.4 upwards and Autofac version 5.2 upwords only.

--

--