Injectio icon indicating copy to clipboard operation
Injectio copied to clipboard

Registration of open generics

Open Tasteful opened this issue 2 years ago • 0 comments

I was adding an open generic class as below that

[RegisterSingleton(Registration = RegistrationStrategy.Self)]
public class DataProtector<TSource, TDestination>
{
}

created the following registration inside the DiscoveredServicesExtensions class

global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAdd(
    serviceCollection,
    global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Describe(
        typeof(global::PublicWeb.DataProtector<TSource, TDestination>),
        typeof(global::PublicWeb.DataProtector<TSource, TDestination>), 
        global::Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton
    )
);

that resulted in msbuild error

error CS0246: The type or namespace name 'TSource' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'TDestination' could not be found (are you missing a using directive or an assembly reference?)

To solve this I was needing to add the ServiceType and ImplementationType as

[RegisterSingleton(Registration = RegistrationStrategy.Self, ServiceType = typeof(DataProtector<,>), ImplementationType = typeof(DataProtector<,>))]
public class DataProtector<TSource, TDestination>
{
}

to get the correct registration

global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAdd(
    serviceCollection,
    global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Describe(
        typeof(global::PublicWeb.DataProtector<,>),
        typeof(global::PublicWeb.DataProtector<,>), 
        global::Microsoft.Extensions.DependencyInjection.ServiceLifetime.Singleton
    )
);

It should be good if the library automatic detecting this open generic and creating correct mapping directly, or has an validation error that describes that open generics not is supported to map.

Using version 2.7.0 of Injectio.

Tasteful avatar Nov 23 '23 10:11 Tasteful