using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Falcon.DI.Test
{
[TestClass]
public class UseFalconDITest
{
///
/// 一般获取服务测试
///
[TestMethod]
public void DITest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
using(var pd = ser.BuildServiceProvider()) {
Assert.IsNotNull(pd.GetServices());
System.Console.WriteLine(pd.GetServices().Count());
Assert.IsTrue(pd.GetServices().Count() > 1);
Assert.IsNotNull(pd.GetService());
}
}
///
/// 测试释放资源
///
[TestMethod]
public void disableTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
var pd = ser.BuildServiceProvider();
var obj = pd.GetService();
Assert.IsNotNull(obj);
Assert.AreEqual(1,MyClassWithDisable.Count);
pd.Dispose();
Assert.AreEqual(0,MyClassWithDisable.Count);
using(pd = ser.BuildServiceProvider()) {
obj = pd.GetService();
Assert.IsNotNull(obj);
Assert.AreEqual(1,MyClassWithDisable.Count);
}
Assert.AreEqual(0,MyClassWithDisable.Count);
}
[TestMethod]
[Description("测试不提供完整构造注入参数")]
public void NotFullTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
var pd = ser.BuildServiceProvider();
var obj = pd.GetService();
Assert.IsNotNull(obj);
Assert.IsNotNull(obj.F1);
Assert.IsNull(obj.F2);
}
///
/// 测试服务工厂
///
[TestMethod]
public void IFalconDIFactoryTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService();
Assert.IsNotNull(obj);
Assert.AreEqual(obj.Instance().Val,2);
var obj2 = pd.GetService>();
Assert.IsNotNull(obj2);
Assert.AreEqual(obj2.Instance().Val,2);
}
}
///
/// 测试注册到自身
///
[TestMethod]
public void RegisterToSelf() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService();
Assert.IsNotNull(obj);
}
}
///
/// 测试单例
///
[TestMethod]
public void SingletonTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
//单例。两次获取为同一对象
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService();
Assert.IsTrue(obj.Val == 0);
obj.Val = 1;
var obj2 = pd.GetService();
Assert.IsTrue(obj.Val == 1);
}
//释放Provider后,释放单例对象
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService();
Assert.IsTrue(obj.Val == 0);
obj.Val = 1;
var obj2 = pd.GetService();
Assert.IsTrue(obj.Val == 1);
}
}
///
/// 测试虚类不能注册
///
[TestMethod]
public void AbstractTest() {
IServiceCollection ser = new ServiceCollection();
ser.UseFalconDI(this.GetType().Assembly);
using(var pd = ser.BuildServiceProvider()) {
var obj = pd.GetService();
System.Console.WriteLine(obj.GetType().FullName);
Assert.IsNotNull(obj);
var cla = obj as ClassFromAbstractWithDi;
Assert.IsNotNull(cla);
}
}
}
}