一、使用自带的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); } }