Tag Archives: SimpleInjector

Perfect console application in .net Core: set up dependency injection

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 SimpleInjector, because I know it well. It’s also quite fast, according to Daniel Palme’s article. Here is how whole calss looks like:

    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 simple naming convention. When interface will have an additional I in the name comparing to it’s class implementation, then it will be automatically registered. No need to remember about such silly things now!

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