一、使用自带的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); } }
二、使用Autofac
1、添加程序包 Autofac 和 Autofac.Extensions.DependencyInjection
Program.cs
IServiceCollection services = new ServiceCollection(); //用Autofac接管 AutofacContainer.Build(services);
AutofacContainer.cs
/// <summary> /// Autofac IOC 容器 /// </summary> public class AutofacContainer { private static readonly ContainerBuilder _builder = new ContainerBuilder(); private static IContainer _container; /// <summary> /// 构建IOC容器 /// </summary> public static IServiceProvider Build(IServiceCollection services) { Assembly iserAss = Assembly.Load("CBest.AFS.Interface"); Assembly serAss = Assembly.Load("CBest.AFS.Service"); //创建serAss中的所有类的instance以此类的实现接口存储 _builder.RegisterAssemblyTypes(iserAss, serAss).AsImplementedInterfaces(); _builder.Populate(services); _container = _builder.Build(); return new AutofacServiceProvider(_container); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Resolve<T>() { return _container.Resolve<T>(); } public static T Resolve<T>(params Parameter[] parameters) { return _container.Resolve<T>(parameters); } public static object Resolve(Type targetType) { return _container.Resolve(targetType); } public static object Resolve(Type targetType, params Parameter[] parameters) { return _container.Resolve(targetType, parameters); } }
具体业务中的使用
private readonly IOrderInfoService _orderInfoService = AutofacContainer.Resolve<IOrderInfoService>();