Last post Jun 30, 2016 06:23 PM by liruikuan
Jun 29, 2016 05:16 PM|liruikuan|LINK
I am using the default service container in asp.net core 1.0 rc2. In my project, I need to register many services, like code below.
//for all type not inherit Assetservices.AddSingleton(typeof(IProvider<>), typeof(Provider<>));
//for those :Asset services.AddSingleton<IProvider<Asset>, AssetProvider<Asset>>(); services.AddSingleton<IProvider<BastionHostAsset>, AssetProvider<BastionHostAsset>>(); services.AddSingleton<IProvider<CloudAccountAsset>, AssetProvider<CloudAccountAsset>>(); services.AddSingleton<IProvider<DeviceAsset>, AssetProvider<DeviceAsset>>(); services.AddSingleton<IProvider<LoadBalanceAsset>, AssetProvider<LoadBalanceAsset>>(); services.AddSingleton<IProvider<VMAsset>, AssetProvider<VMAsset>>(); services.AddSingleton<IProvider<StoreAllocAsset>, AssetProvider<StoreAllocAsset>>();
Unlike all the generic types register at the first line code, I have to register every type which inherits Asset line by line, boring work.
Can I improve the code more simple? I wish there is one line code to register
all the providers for types inheriting Asset, may be like below:
services.AddSingleton<IProvider<T>,AssetProvider<T>> where T: Asset
How should I improve my code ?
Jun 29, 2016 09:10 PM|bruce (sqlwork.com)|LINK
just add a helper extension:
public static void AddSingletonAsset<T>(this IServiceCollection services) where T: Asset
Jun 30, 2016 12:35 AM|liruikuan|LINK
Thanks for reply.
Maybe I still don't understand, but by using this helper extension, do I have to write many lines caller code for types?
It seems can't reduce the line count, and if I add one more Asset Provider, I have to modify my register code.
Jun 30, 2016 02:08 PM|maherjendoubi|LINK
services.AddSingleton<IProvider<T>, AssetProvider<T>>(); ---> it is generic and replace all the lines you wrote.
Jun 30, 2016 02:37 PM|liruikuan|LINK
But the T is open type, I can't direct write it in my code...
In my project, there are two kinds of types, some are not asset, the others are asset, I need to give them different providers: defaultProvider or assetProvider.
I think I know what you mean to some degree, both of you, but I still can't write the code passing the compiler.
Would you please write down the can-work code? I wish to learn.
Jun 30, 2016 03:05 PM|bruce (sqlwork.com)|LINK
if you want to use reflection instead of manual configuration see docs:
you could use a naming convention, or attribute to find the services. but its pretty simple.
Jun 30, 2016 03:06 PM|maherjendoubi|LINK
Would you please share your project somewhere that I could have a look?
Jun 30, 2016 06:23 PM|liruikuan|LINK
It seems that the default service container doesn't provide these features.
I will study autofac later.
Thanks again, both of you.