且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在.NET Core控制台应用程序中使用Microsoft.Extensions.DependencyInjection?

更新时间:2023-02-17 21:34:02

我基本上像这样使用它:

安装nuget Microsoft.Extensions.DependencyInjection

然后在Program.cs中

 使用Microsoft.Extensions.DependencyInjection;公共课程{公共静态无效的Main(string [] args){var services = new ServiceCollection().AddSingleton< WhateverType>(新的WhateverType());var serviceProvider = services.BuildServiceProvider();serviceProvider.GetService< WhateverType>().DoWork();}} 

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:

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();
        }
    }