在上一节:手把手教你写DI_0_DI是什么?html
咱们已经理解DI是什么app
接下来咱们就徒手撸一撸,玩个支持构造函数注入的DI出来框架
首先咱们回顾一下 构造函数注入 的代码形式, 大概长这模样:ide
class MovieLister { private IMovieFinder finder; public MovieLister(IMovieFinder finder) { this.finder = finder; } }
那么咱们就能够动手撸了函数
Emmmm...ui
等等,这个finder 从哪来? 咱们本身new吗?本身new,咱们还要DI干什么?又不是找对象this
好吧,咱们参照一下Microsoft.Extensions.DependencyInjection
的设计,毕竟咱们是小白,什么都不懂设计
其使用例子大体是这样:code
var provider = new ServiceCollection() // 声明服务定义集合,能够理解为 咱们你们公司初创,要列出咱们要招聘哪些人才干活 .AddTransient<IXX,XX>() // 添加一个瞬态的服务定义,也就是咱们的招聘广告 // 对你们这些老板来讲能够把 XX 这个“人”(类) 当成 IXX 这种“畜生”(接口)同样奴役,好比咱们广告就是要个长得漂亮,手艺好,会IXX的搬砖工 // 瞬态能够理解成 咱们的这份活儿比较危险,一我的干完一次以后就无法再干了,因此每次有活儿,咱们都得从新招人 .BuildServiceProvider(); // 这是建立DI构造入口,能够理解成咱们把招聘广告交给人才市场了,每次咱们要干什么活儿,就能够打个电话叫人啦 var xx = provider.GetService(typeof(IXX)); // 等同于咱们打个电话:喂,人才市场的蛇头吗? 咱们要个会IXX的搬砖的。 等一下子,蛇头就把会IXX送上咱们的门啦 xx.DoSomethings(); // 等同于 xx 你去给我搬砖
哦哦哦,咱们就是要撸这样的东西出来嗦server
那咱们看看每一个都长啥鬼模样
ServiceCollection
:
public class ServiceCollection : IServiceCollection { } // // Summary: // Specifies the contract for a collection of service descriptors. public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable { }
哦哦,就是 ServiceDescriptor
集合嘛
AddTransient
:
public static IServiceCollection AddTransient<TService, TImplementation>(... var descriptor = new ServiceDescriptor(serviceType, implementationFactory, lifetime); collection.Add(descriptor); return collection;
哦哦,也就是 add ServiceDescriptor
嘛
ServiceDescriptor
:
public class ServiceDescriptor { public ServiceDescriptor(Type serviceType, Type implementationType, ServiceLifetime lifetime); ... // // Summary: // Specifies the lifetime of a service in an Microsoft.Extensions.DependencyInjection.IServiceCollection. public enum ServiceLifetime { // // Summary: // Specifies that a single instance of the service will be created. Singleton = 0, // // Summary: // Specifies that a new instance of the service will be created for each scope. // // Remarks: // In ASP.NET Core applications a scope is created around each server request. Scoped = 1, // // Summary: // Specifies that a new instance of the service will be created every time it is // requested. Transient = 2 }
哦哦哦,ServiceDescriptor
就是一些描述嘛
那BuildServiceProvider
呢 ?
public static IServiceProvider BuildServiceProvider(this IServiceCollection services) { ... return new ServiceProvider(xxx); } // // Summary: // Defines a mechanism for retrieving a service object; that is, an object that // provides custom support to other objects. public interface IServiceProvider { // // Summary: // Gets the service object of the specified type. // // Parameters: // serviceType: // An object that specifies the type of service object to get. // // Returns: // A service object of type serviceType. -or- null if there is no service object // of type serviceType. object GetService(Type serviceType); }
索嘎,咱们实现这些抽象就好啦
来,让咱们思考一下,怎么撸成这些抽象的实现
下一章咱们再讨论