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

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.

--

--

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