Cannot use constructors in open generic services with Kephas

走远了吗. 提交于 2020-01-15 09:21:11

问题


Somehow I cannot get to make it work having a service exported as open generic with an implementation with a constructor. I tried to add the [CompositionConstructor] attribute to it to no avail. It throws something like:

System.Composition.Hosting.CompositionFailedException : No importing constructor was found on type 'MyType'.

Any ideas?


回答1:


Unfortunately this is a bug in the System.Composition library (check here https://github.com/dotnet/corefx/issues/40094). As I can see, this bug is added to the 5.0 milestone, meaning next year in autumn. From my perspective you have the following options:

  1. Leave the implementation class only with the default constructor. Here you can use AmbientServices.Instance.CompositionContainer.GetExport to get the dependencies you need. I know it is not the best solution, but it should work. Warning: if the service is marked as scoped, than if you depend on other scoped services you will not get the right scope for them.

  2. Kephas version 6.5.0 brings an Autofac implementation for Kephas composition, where the things work as they suppose to be. Check the sources at https://github.com/kephas-software/kephas/releases to get the latest version and build the nugets you need. I will try to publish a beta version on nuget soon.

  3. Bring your own implementation of composition for the version you use, with your DI container of choice. You could take as reference the Autofac implementation, although there are a couple of breaking changes in the latest version. When choosing a DI container, make sure it supports open generics, metadata, and a way to support the IExportFactory interfaces.



来源:https://stackoverflow.com/questions/57623652/cannot-use-constructors-in-open-generic-services-with-kephas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!