implementationFactory for Open Generics
prasannapattam opened this issue ยท 8 comments
I am looking to use a Factory to create the generic object. I want the generic object type passed on to the implementation factory so that I can create the object based on the generic type.
services.AddTransient(typeof(ServiceDocument<>),
// I need to get the closed generic type here so that the corresponding object is created, i.e., ServiceDocument<Employee>
p => new ServiceDocument<Employee>()
);
As you see in the above code, in the implementationFactory function, I want to create the object based on the generic type, for example:
- For ServiceDocument<Employee>, I need to create the ServiceDocument<Employee>
- For ServiceDocument<Department>, I have to create the ServiceDocument<Department> object
Is there a way the DI can pass in the object type to this factory function?
There's no way to access this today. Is there any way you can avoid using a factory? Or just use a closed generic.
I can do a workaround with constructor.
I recommend enhancing the factory to support this functionality. I see this is a good feature.
@prasannapattam The biggest problem is understanding of other containers can flow this context to their factory implementations.
I can see this is a problem on making this work for other containers.
Is it possible to create an overload which works for the default DI. Something like
Func<IServiceProvider, Type, object> implementationFactory
I think I've asked for this before (but maybe not filed and issue) in order to support decoration of open generics, so consider this my ๐
I think I've asked for this before (but maybe not filed and issue) in order to support decoration of open generics, so consider this my ๐
Are you willing to do the research to see if all existing container adapters support this?
I really don't see how this can be supported without doing MakeGenericType somewhere in the factory implementation. That would not be all that efficient
Closing because we are not planning on adding this feature to the default DI container.