How to inject services in a controller inside a re

2019-06-10 08:12发布

问题:

I am using a Razor Class Library for making a reusable complex View (which includes its controller and several View Components) that can be used across several ASP.NET Core MVC projects. The problem is that the controller use dependency injection (a custom service called "GatewayProxy" and string localization). What is the correct way to inject services into a controller inside a RCL?

Here is the structure of my RCL:

Here is the exception:

回答1:

You mentioned how you fixed this by adding the dependencies to Startup.cs of your main project. But consider that any consumer of this reuseable library may not remember (or know) what dependencies are needed for your library.

Something you can do to solve this is to create an extension off of IServiceCollection in your Rcl that does the dependency registration.

public static void AddMyRclServices(this IServiceCollection serviceCollection, IConfiguration config)
{
    serviceCollection.AddTransient<IRclService1, RclService1>();
    serviceCollection.AddScoped<IRclService2, RclService2>();
}

Then in Startup.cs for your MVC project call the extension

using Rcl.Extensions

public void ConfigureServices(IServiceCollection services)
{
    services.AddMyRclServices(config);
}