.Net Core 控制台应用程序 依赖注入

一、使用自带的IOC容器

参考自 https://www.cnblogs.com/dudu/p/5552293.html

1、添加程序包 Microsoft.Extensions.DependencyInjection

修改Program.cs

IServiceCollection services = new ServiceCollection();
//注入
services.AddTransient<IMemcachedClient, MemcachedClient>();
services.AddTransient<MyTest>();
//构建容器
IServiceProvider serviceProvider = services.BuildServiceProvider();

//调用业务
var myTest = serviceProvider.GetService<MyTest>();
myTest?.test();

MyTest.cs代码

internal class MyTest
    {
        private IMemcachedClient _memcachedClient;
     //构造函数注入 public MyTest(IMemcachedClient memcachedClient) { _memcachedClient = memcachedClient; } public void test() { DateTime datetime = _memcachedClient.getTime(); Console.WriteLine(datetime); } }

.Net Core 控制台应用程序 依赖注入

 

上一篇:Apache负载均衡配置(反向代理模式)


下一篇:两个线程交替执行