泛型注册

使用 Register 方法实现泛型注册

注册泛型与注册非泛型的方式几乎一致。

示例 :注册泛型类型

  1. using System;
  2. using System.Linq;
  3. using DryIoc;
  4. using NUnit.Framework;
  5. class Register_open_generic
  6. {
  7. [Test]
  8. public void Example()
  9. {
  10. var container = new Container();
  11. // 这里在 Register 方法中传入 typeof(ICommand<>) 指定泛型类型
  12. container.Register(typeof(ICommand<>), typeof(DoSomethingCommand<>));
  13. var cmd = container.Resolve<ICommand<MyData>>();
  14. Assert.IsInstanceOf<DoSomethingCommand<MyData>>(cmd);
  15. }
  16. interface ICommand<T> { }
  17. class DoSomethingCommand<T> : ICommand<T> { }
  18. struct MyData { }
  19. }

示例 :注册泛型类型

  1. class Open_generic_registrations
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container();
  7. // 默认注册
  8. container.Register(typeof(Command<>));
  9. // 这里使用 Reuse 指定服用方式
  10. container.Register(typeof(Command<>), Reuse.Singleton);
  11. // 这里使用 IfAlreadyRegistered.AppendNewImplementation,表示若类型已注册,则为该类型添加新的注册
  12. container.Register(typeof(ICommand<>), typeof(Command<>),
  13. ifAlreadyRegistered: IfAlreadyRegistered.AppendNewImplementation,
  14. serviceKey: "blah");
  15. // 这里使用 Setup.Decorator
  16. container.Register(typeof(ICommand<>), typeof(LoggingCommand<>),
  17. setup: Setup.Decorator);
  18. // etc.
  19. }
  20. interface ICommand<T> { }
  21. class Command<T> : ICommand<T> { }
  22. class LoggingCommand<T> : ICommand<T> { }
  23. }

解析单个服务类型时,封闭类型的注册优先级要高于对应的开发类型的注册:

示例 :解析泛型对象的优先级

  1. class Closed_is_preferred_over_open_generic
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container();
  7. container.Register<A<int>, BInt>();
  8. container.Register(typeof(A<>), typeof(B<>));
  9. var a = container.Resolve<A<int>>(); // 这类解析出来的是 BInt 类型
  10. Assert.IsInstanceOf<BInt>(a);
  11. // 解析集合时(数组),将会解析该服务类注册的所有实现类,集合的数量等于实现类的注册数量。
  12. var items = container.Resolve<A<int>[]>();
  13. // Assert通过,数组中包含 Bint 与 B<int>
  14. Assert.AreEqual(2, items.Length);
  15. }
  16. class A<T> { }
  17. class BInt : A<int> { }
  18. class B<T> : A<T> { }
  19. }

匹配类型参数约束

在解析集合类型时,基于泛型约束条件实现过滤

示例 :泛型约束条件过滤

  1. class Matching_open_generic_type_constraints
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container();
  7. // 同时注册两个类型,通过 nonPublicServiceTypes = true 允许非public服务类也可以注册
  8. container.RegisterMany(new[] { typeof(A<>), typeof(B<>) }, nonPublicServiceTypes: true);
  9. var items = container.Resolve<I<string>[]>();
  10. // Assert通过,受制于类型约束,string 类型并非继承自 IDisposable,因此无法解析 A<string> 对象,数组集合仅有一个 B<string> 类型对象。
  11. Assert.AreEqual(1, items.Length);
  12. Assert.IsInstanceOf<B<string>>(items[0]);
  13. }
  14. interface I<T> { }
  15. class A<T> : I<T> where T : IDisposable { }
  16. class B<T> : I<T> { }
  17. }

针对上述例子,假设 nonPublicServiceTypes = false (默认值),由于A、B均为非public类型,因此将会抛出异常:

  1. container.RegisterMany(new[] { typeof(A<>), typeof(B<>) }, nonPublicServiceTypes: false);

异常信息 :
DryIoc.ContainerException:“code: Error.NoServicesWereRegisteredByRegisterMany;
message: No service types were discovered in RegisterMany (or in RegisterInstanceMany) for the specified implementation types:
[ConsoleApp1.A<>,
ConsoleApp1.B<>]
Maybe you missed the implementation or service type(s), e.g. provided only abstract or compiler-generated implementation types, or specified a wrong serviceTypeCondition,or did not specify to use nonPublicServiceTypes, etc.”
**

从泛型约束中识别并填写类型参数



  1. class Fill_in_type_arguments_from_constraints
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container();
  7. container.Register(typeof(ICommandHandler<>), typeof(UpdateCommandHandler<,>));
  8. var handler = container.Resolve<ICommandHandler<UpdateCommand<MyEntity>>>();
  9. Assert.IsInstanceOf<UpdateCommandHandler<MyEntity, UpdateCommand<MyEntity>>>(handler);
  10. }
  11. public interface ICommandHandler<TCommand> { }
  12. public class SpecialEntity { }
  13. public class UpdateCommand<TEntity> { }
  14. public class UpdateCommandHandler<TEntity, TCommand> : ICommandHandler<TCommand>
  15. where TEntity : SpecialEntity
  16. where TCommand : UpdateCommand<TEntity>
  17. { }
  18. public class MyEntity : SpecialEntity { }
  19. }

从上述例子可以看出,DryIoc 十分智能,能够使用将 MyEntity 作为 UpdateCommandHandler 函数的首个参数类型。

支持“变体”泛型的解析

支持“协变”泛型(默认开启支持)

示例 :支持“协变”

  1. class Generic_variance_thingy
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. var container = new Container();
  7. container.Register<IHandler<A>, AHandler>();
  8. container.Register<IHandler<B>, BHandler>();
  9. // get all handlers of A
  10. var aHandlers = container.ResolveMany<IHandler<A>>();
  11. // Assert通过,集合中包含 AHandler 和 BHandler,因为 IHandler<B> 通过协变类型继承自 IHandler<A>
  12. Assert.AreEqual(2, aHandlers.Count());
  13. // Assert通过,集合中仅包含 BHandler
  14. var bHandlers = container.ResolveMany<IHandler<B>>();
  15. Assert.AreEqual(1, bHandlers.Count());
  16. }
  17. // 通过 out 关键词,将 TEvent 参数声明为 “协变” 类型
  18. public interface IHandler<out TEvent> { } // covariant handler
  19. public class A { }
  20. public class B : A { }
  21. public class AHandler : IHandler<A> { }
  22. public class BHandler : IHandler<B> { }
  23. }


关于“协变”泛型

具有协变类型参数的接口使其方法返回的类型可以比类型参数指定的类型派生程度更大。 例如,因为在 .NET Framework 4 的 IEnumerable 中,类型 T 是协变的,所以可以将 IEnumerable(Of String) 类型的对象分配给 IEnumerable(Of Object) 类型的对象,而无需使用任何特殊转换方法。

  • 使用 out 关键词,声明为“协变”类型 ```csharp public interface IHandler { } // covariant handler public class A { } public class B : A { } public class AHandler : IHandler { } public class BHandler : IHandler { }

// Bhandler 可以隐式转换为 IHandler IHandler a = new BHandler();

  1. - 移除 out 关键词,声明为“一般”泛型
  2. ```csharp
  3. public interface IHandler<TEvent> { } // covariant handler
  4. public class A { }
  5. public class B : A { }
  6. public class AHandler : IHandler<A> { }
  7. public class BHandler : IHandler<B> { }
  8. // 抛出异常
  9. IHandler<A> a = new BHandler();

异常信息 :(编译时错误)
无法将类型“ConsoleApp1.BHandler”隐式转换为“ConsoleApp1.IHandler”。存在一个显式转换(是否缺少强制转换?)
**

关闭对“协变”泛型的支持

示例 :关闭“协变”支持

  1. class Turn_off_generic_variance_in_collections
  2. {
  3. [Test]
  4. public void Example()
  5. {
  6. // 这里通过 WithoutVariantGenericTypesInResolvedCollection 方法,取消对变体泛型的支持
  7. var container = new Container(rules =>
  8. rules.WithoutVariantGenericTypesInResolvedCollection());
  9. container.Register<IHandler<A>, AHandler>();
  10. container.Register<IHandler<B>, BHandler>();
  11. // Assert通过,集合中仅包含 AHandler
  12. var aHandlers = container.ResolveMany<IHandler<A>>();
  13. Assert.AreEqual(1, aHandlers.Count());
  14. }
  15. public interface IHandler<out TEvent> { } // covariant handler
  16. public class A { }
  17. public class B : A { }
  18. public class AHandler : IHandler<A> { }
  19. public class BHandler : IHandler<B> { }
  20. }