dependency-injectioncompositionkephas

Cannot use constructors in open generic services with Kephas


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?


Solution

  • 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.