Resolving wrapper classes in C# with the Unity IoC container

后端 未结 2 1076
离开以前
离开以前 2021-01-03 14:46

I want to use Unity resolve IService to two different implementations, to make use of a wrapper class, the equivalent of:

 IService service = new         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-03 15:19

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

    container.RegisterType("real");
    container.RegisterType("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.

    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.

提交回复
热议问题