Create a dotnet core Cosnole app template with autofac dependency injections

Precise Agency
2 min readSep 12, 2020
dotnet core console app with autofac

Every time I create a new project, I have to go through exactly same steps to setup some open source libraries that I always use for any projects.

For example I often use autofac as my dependency inject container and register a bunch of services and preconfigure them the same way, such as Serilog, Automapper, etc.

There is nothing difficult to setup all these libraries, it is just time consuming and repetitive job that has to be done every single time.

So here I create this small template project that is pre-installed and pre-configured with all these libraries, to speed up your development process.

Install and use the template

This is the link to the published nuget package as a dotnet template,

You can install this template via nuget using dotnet new -i,

dotnet new --install Superwalnut.NetCoreConsoleTemplate

The template will be installed as core-console-autofac.

Then you can create your new project using this template,

dotnet new core-console-autofac -n MyFirstConsole

What is included in your new project

---- Models 
|---- Foo.cs
---- Modules
|---- ConsoleModules.cs
---- AutoMapper
|---- MyAutoMapperProfile.cs
---- appsettings.json
---- Program.cs
---- Startup.cs

Autofac

I created a Startup.cs file to create autofac ContainerBuilder and register all the services using ConfigureServices() method. To keep service registrations neat and clean, I created an autofac module, for the services only consumed by the console app.

appsettings.json

I need to use ConfigurationBuilder(), to read the physical app setting json file from its environment, and then AddEnvironmentVariables(), so we can override configurations via environment variables.

Serilog

Registered the logger in ConfigureService(),

and configured with Console output sinks.

AutoMapper

Created a default automapper profile with an example CreateMap().

Finally,

Congratulations on setup your .net core console app with this template. If you find my article is helpful and saving you some time, please follow me at Medium and share this post with your mates.

Here is a link to github to grab the full source code.

--

--

Precise Agency

I am exploring web dev trends in areas like .net, serverless, react, angular, etc. & using medium as an amazing platform to improve my skills and share my code