khellang / Scrutor

Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
MIT License
3.58k stars 234 forks source link

Register services with ImplementationFactory #211

Open LeonxPRO opened 1 year ago

LeonxPRO commented 1 year ago

Hello! First, thanks for a Scrutor) Is it any way for register services with ImplementationFactory, like in native IServiceCollectionmethod ? AddSingleton<TService>(Func<IServiceProvider, TService> implementationFactory) I imagine that like:

IServiceCollection collection = _serviceCollection.Scan(scan => scan.FromAssemblies(ass)
.AddClasses(classes => classes.AssignableTo<TService>(), false)
.AsImplementedInterfaces()
.WithSingletonLifetime(Func<IServiceProvider, TService> implementationFactory))

instead WithSingletonLifetime()

khellang commented 1 year ago

Hello @LeonxPRO! 👋🏻

The issue with providing a factory like that is that it needs to work for all subtypes of TService, so you it would also have to know the specific type that it's trying to register in the callback.

I'd love to know a bit more about what you're trying to do. Do you have a concrete example?

carlhoogstoel commented 11 months ago

Sample is pretty straighforward, just have a bunch of classes that have the same interface for wich you want to have a property filled during creation.

.WithSingletonLifetime(Func<IServiceProvider, TService> implementationFactory)) would be awesome :)

kdrcetintas commented 1 month ago

Any progress on this one? Basically it would be nice to get a callback for instance creation; (IServiceProvider, Type concreteType)