1、安装引用Nuget包
1)使用Nuget管理控制台
集成到项目中的最简单方法是使用NuGet。您可以通过打开包管理器控制台(PM)并键入以下语句来安装依赖:
Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.DependencyInjection.Abstractions
2)使用Nuget图形管理器
使用Nuget的界面的管理器分别搜索:
"Microsoft.Extensions.DependencyInjection"
"Microsoft.Extensions.DependencyInjection.Abstractions"
=> 然后找到点击 "安装"
。
3)使用.NET CLI命令安装
> dotnet add TodoApi.csproj package Microsoft.Extensions.DependencyInjection
> dotnet add TodoApi.csproj package Microsoft.Extensions.DependencyInjection.Abstractionss
相关文档:VS(Visual Studio)中Nuget的使用
2、构造函数传递参数示例代码
using Microsoft.Extensions.DependencyInjection;
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddTransient<HelloWorldService>();
services.AddTransient(p => p.ResolveWith<DemoService>("Tseng", "Stackoverflow"));
var provider = services.BuildServiceProvider();
var demoService = provider.GetRequiredService<DemoService>();
Console.WriteLine($"Output: {demoService.HelloWorld()}");
Console.ReadKey();
}
}
public class DemoService
{
private readonly HelloWorldService helloWorldService;
private readonly string firstname;
private readonly string lastname;
public DemoService(HelloWorldService helloWorldService, string firstname, string lastname)
{
this.helloWorldService = helloWorldService ?? throw new ArgumentNullException(nameof(helloWorldService));
this.firstname = firstname ?? throw new ArgumentNullException(nameof(firstname));
this.lastname = lastname ?? throw new ArgumentNullException(nameof(lastname));
}
public string HelloWorld()
{
return this.helloWorldService.Hello(firstname, lastname);
}
}
public class HelloWorldService
{
public HelloWorldService() {
}
public string Hello(string name) => $"Hello {name}";
public string Hello(string firstname, string lastname) => $"Hello {firstname} {lastname}";
}
// Just a helper method to shorten code registration code
static class ServiceProviderExtensions
{
public static T ResolveWith<T>(this IServiceProvider provider, params object[] parameters) where T : class =>
ActivatorUtilities.CreateInstance<T>(provider, parameters);
}
}
相关文档:
.NET Core(C#) Console控制台项目中使用DI依赖注入(ConfigureServices)
.NET Core 2.0控制台程序(console)安装配置使用NLog的方法及示例代码
.NET Core(C#)运行控制台程序(console app)的命令方法
.NET Core(console)应用程序中发布创建独立可执行(.exe)文件
.NET Core 2.0 console(控制台)项目 Microsoft.Extensions.Logging NLog配置使用