且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Unity IoC容器解析C#中的包装器类

更新时间:2022-05-08 23:23:53

您可以使用RegisterType重载,该重载接受基于字符串的名称.在这种情况下,您将执行以下操作:

You can use RegisterType overloads that accept string based names. In this case you'll do something like:

container.RegisterType<IService, RealService>("real");
container.RegisterType<IService, DispatcherService>("dispatcher");

并使用名称声明您的依赖关系.

and announce your dependencies with names as well.

[Dependency("real")]

这将使您避免在大多数情况下不是一个好主意的标记界面.

This will allow you to avoid marker interface which is in most cases is not a good idea.

但是,如果要保持代码在Unity中的存在(如DependencyAttribute),并且在大多数情况下,在应用程序生命周期内仅使用一种实现(例如,仅使用DispatcherService),您基本上可以决定是否需要是否用DispatcherService包装请求的IService.在这种情况下,您可以查看静态工厂扩展团结.工厂代表将了解配置,并且基于配置的情况是将IService与DispatcherService包装在一起,或者仅返回从容器获取的IService实现.

However if want to keep your code clean from Unity presence (like DependencyAttribute) and in most cases you will use only 1 implementation during application lifetime (for example, only DispatcherService will be used) you basically to make decision whether you need to wrap requested IService with DispatcherService or not. In this case you can look at Static Factory Extension for Unity. Factory delegate will be aware of configuration and based on configuration will either wrap IService with DispatcherService or simply return IService implementation obtained from container.