dependency injection .net core code example

Example 1: add dependency injection .net core console app

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

public class Program
{
    public static void Main(string[] args)
    {
        //setup our DI
        var serviceProvider = new ServiceCollection()
            .AddLogging()
            .AddSingleton<IFooService, FooService>()
            .AddSingleton<IBarService, BarService>()
            .BuildServiceProvider();

        //configure console logging
        serviceProvider
            .GetService<ILoggerFactory>()
            .AddConsole(LogLevel.Debug);

        var logger = serviceProvider.GetService<ILoggerFactory>()
            .CreateLogger<Program>();
        logger.LogDebug("Starting application");

        //do the actual work here
        var bar = serviceProvider.GetService<IBarService>();
        bar.DoSomeRealWork();

        logger.LogDebug("All done!");

    }
}

Example 2: add dependency injection .net core console app

{
  "dependencies": {
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.DependencyInjection": "1.0.0"
  }
}

Example 3: register all services microsoft .net core dependency injection container

service.RegisterAssemblyPublicNonGenericClasses(… your assembly ref goes here …)
.Where(x => x.Name.EndsWith(“Service”))  //optional
.IgnoreThisInterface<IMyInterface>()     //optional
.AsPublicImplementedInterfaces(ServiceLifetime.Scoped);