It may seem that when creating a console application we are doomed to use statics all over the code. Well.. we’re not! I’ll show you how to set up dependency injection and use it.
This is a part of a series of articles about writing a perfect console application in .net core 2. Feel free to read more:
Dependency Injection
There are many packages that can provide dependency injection, but I chose
using System.Linq; using SimpleInjector; public static class ContainerConfig { private static Container Container; public static void Init() { Container = new Container(); RegisterAllTypesWithConvention(); Container.Verify(); } public static TService GetInstance<TService>() where TService : class { return Container.GetInstance<TService>(); } private static void RegisterAllTypesWithConvention() { var typesWithInterfaces = typeof(Program).Assembly.GetExportedTypes() .Where(t => t.Namespace.StartsWith("MichalBialecki.com.TicketStore")) .Where(ts => ts.GetInterfaces().Any() && ts.IsClass).ToList(); var registrations = typesWithInterfaces.Select(ti => new { Service = ti.GetInterfaces().Single(), Implementation = ti }); foreach (var reg in registrations) { Container.Register(reg.Service, reg.Implementation, Lifestyle.Singleton); } } }
Notice RegisterAllTypesWithConvention method – it is the way to register all interface implementations, that follows a
No more statics in .net core all over the code 🙂
All code posted here you can find on my GitHub: https://github.com/mikuam/console-app-net-core
A lot of ppl that are still using their old IoC containers instead of the built-in one in .NET Core because of the methods like `RegisterAllTypesWithConvention`. https://github.com/khellang/Scrutor project has these kinds of auto-wiring and it’s just an extension and not a new IoC container.
I’d rather use the same dependency injection engine used by asp.net core if possible.
Luciano,
It is possible however, I don’t think it’s the best idea. You can use ‘built it’ DI, which comes with Microsoft.Extensions.DependencyInjection package. Nevertheless, SimpleInjector offers much more and is quite fast.