Cleaner Dependency Injection in .Net Core

Posted On: 12/5/2018 6:38:25 PM

Filed Under: Programming / .Net Core


Here I gave a very basic example of easily setting up Dependency Injection in .Net Core.

I write these things as I discover them, and as you may already know - the time of discovery doesn't always allow for the best engineering.  I've since pulled the code out of the Startup.cs, and segregated it off into its own static class.  Another huge flaw was: any interface I created later would have to have the same method repeated.  Of course, this hit me in the face almost immediately as I wanted injectable managers.

Well, here is a trimmed down version:

 

        private static void RegisterInjectedInterfaces(Type injectableType, IServiceCollection services)
        {
            var type = injectableType;
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
            foreach (var t in types)
            {
                services.AddTransient(t);
            }

        }

        public static void InitDependencies(IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<ngCmsDbContext>(options =>
                options.UseSqlServer(configuration.GetConnectionString("ngCmsConnectionString"), c => c.MigrationsAssembly("ngCmsBase.Web")));

            services.AddScoped(typeof(IRepository<,>), typeof(Repository<,>));

            RegisterInjectedInterfaces(typeof(IngServiceBase), services);
            RegisterInjectedInterfaces(typeof(IngManagerBase), services);

        }
    }

The next step would be to have one incredibly generic interface, say: IInjectable - and create abstract or partial classes which inherit from it - and this way I never have to touch this class again!


Comments