Basically in Asp.Net Core
we register services inside startups.cs
file. Now the question is , is there any extensibility point in Asp.Net Core
giving us the chance to hook into some kind of registrar method (by implementing a specific interface for example) and don't mess up with startup.cs
?
Startup
If you just want to avoid making a mess in Startup.cs
just delegate the service registration logic to another method, perhaps in another static class.
ServiceRegistry.RegisterAllServices(services);
If you really want to hack your way into startup logic of ASP.Net I'm afraid you're out if luck. The build up of the ServicesCollection takes place in the BuildCommonServices method. As you can see there is no easy way to hook into the logic here.
In short what happens when an ASP.Net
app start is the following:
.Net core
there is only one app model - Console Apps; so Main
is called. Configure
, ConfigureContainer
and ConfigureServices
. startupType
and the startupType
only. ( REF ) Registering additional services into the IOC Container
that comes with ASP.Net Core
is not trivial.
The DI Framework itself is very basic and if you find yourself trying to do something that is not trivial you probably should upgrade yourself to a more mature and feature complete IOC Container
.
You can find some links in the README file on the aspnet/DependencyInjection repository on GitHub.
I have to note though, registering services after the container is created is considered a bad practice.
Good answer here already, but just to add my 2c.
I think what you are essentially looking for is something like "Profiles" or "Modules" and the IOC does an assembly scan. You can do this already, but you would need to create your own interface/reflection code.
Another option is to use the ServiceCollection Extension pattern which seems to be the default way to add "services".
For example take this code :
public static class ServicesConfiguration
{
public static void AddCustomServices(this IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
}
}
Then your Configure Services method would look more like :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCustomServices();
}
In some ways I prefer this as you can still at a glance see what is being loaded in and follow the trail rather than having some mystery reflection going on.
Further reading : http://dotnetcoretutorials.com/2017/01/24/servicecollection-extension-pattern/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.