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