Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Microsoft.Extensions.DependencyInjection in an .NET Core console app?

I have a library that I would like to run on all platforms supported by .NET Core (Xamarin, Windows, Mac). And to do this I need to have a cross platform DI to handle the platform specific customizations such as storage, security, etc.

All of the examples I've seen for Microsoft.Extensions.DependencyInjection include code for ASP.NET Core. Does any equivalent / supported scenario exist for a console app?

Alternatively (ideally) I would like the DI framework used for the console to work for ASP.NET Core, Xamarin, and Win32

Error Example

I'm using this code as the basis for my .NET Core application. It appears that ServiceCollection should be public, but when I use Xamarin on the Mac the default implementation of IServiceCollection (ServiceCollection) is missing:

enter image description here

like image 345
TLDR Avatar asked Dec 18 '18 01:12

TLDR


1 Answers

I use it basically like so:

Install nuget Microsoft.Extensions.DependencyInjection

Then in Program.cs

using Microsoft.Extensions.DependencyInjection;

 public class Program
    {
        public static void Main(string[] args)
        {

            var services = new ServiceCollection()
                .AddSingleton<WhateverType>(new WhateverType());

            var serviceProvider = services.BuildServiceProvider();


            serviceProvider.GetService<WhateverType>().DoWork();
        }
    }
like image 121
zaitsman Avatar answered Nov 05 '22 06:11

zaitsman