如何在.NET Core控制台应用程序中使用Microsoft.Extensions.DependencyInjection? [英] How can I use Microsoft.Extensions.DependencyInjection in an .NET Core console app?
问题描述
我有一个要在.NET Core支持的所有平台(Xamarin,Windows,Mac)上运行的库.为此,我需要一个跨平台的DI来处理特定于平台的自定义项,例如存储,安全性等.
我为 Microsoft.Extensions.DependencyInjection
看到的所有示例都包含ASP.NET Core的代码.控制台应用程序是否存在任何等效/受支持的方案?
(理想情况下)我希望用于控制台的DI框架适用于ASP.NET Core,Xamarin和Win32
错误示例
我正在使用
我基本上像这样使用它:
安装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();
}
}
这篇关于如何在.NET Core控制台应用程序中使用Microsoft.Extensions.DependencyInjection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!