Dependencyinjection: implementationFactory for Open Generics

Created on 17 Jan 2017  路  8Comments  路  Source: aspnet/DependencyInjection

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.

```c#
services.AddTransient(typeof(ServiceDocument<>),
// I need to get the closed generic type here so that the corresponding object is created, i.e., ServiceDocument
p => new ServiceDocument()
);

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, I need to create the ServiceDocument
  • For ServiceDocument, I have to create the ServiceDocument object
    ```

Is there a way the DI can pass in the object type to this factory function?

wontfix

Most helpful comment

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 :+1:

All 8 comments

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 :+1:

@khellang @prasannapattam

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MatthewLymer picture MatthewLymer  路  9Comments

GrabYourPitchforks picture GrabYourPitchforks  路  14Comments

davidfowl picture davidfowl  路  24Comments

davidfowl picture davidfowl  路  47Comments

d0apga picture d0apga  路  3Comments