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:
Dependency Injection (DI) is a technique that promotes loose coupling of software through separation of concerns.
If one or more common services are required by the Server and Client projects of a hosted Blazor WebAssembly solution, you can place the common service registrations in a method in the Client project and call the method to register the services in both projects.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With